Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Brain Candy
May 18, 2006

triplekungfu posted:

What type is name in the Product class? If it's a String already, you don't need those casts to String. It's only a minor issue, but every time I see stuff like that at work I die a little.

String is final, so name is either a String or an Object (or CharSequence or Comparable<String>(!)). :suicide:

Brain Candy fucked around with this message at 12:56 on Mar 5, 2008

Adbot
ADBOT LOVES YOU

Brain Candy
May 18, 2006

triplekungfu posted:

If you're not concerned with performance you could use the apache commons SerializationUtils; as mentioned in the javadoc, all objects you want cloned must implement Serializable (which ArrayList implements already).

Use it if you aren't concerned about good programming or sanity either. This seems like a horrible abuse of Serialization, which is supposed be about passing objects across a network. ArrayList also has a copy-constructor so if the data is immutable its very easy, otherwise use foreach loops. Manually copying data from one instance to another is not going to be that bad.

There is an problem with marker interfaces (interfaces that don't actually require methods, including Cloneable and Serializable) in that you can't get rid of them in subclasses.

1337JiveTurkey posted:

Immutable objects are also a possible alternative. If you're not constantly modifying a class of objects, you can get around all of that by just creating a new object for every change. Immutable objects work well with each other because any two objects can share a third object without needing to worry if the third object will change underneath them. This reduces memory usage requirements and makes it easier to turn other objects immutable if all of their fields are immutable.

Immutable objects definitely nice for many things, but they come at a price. Strings, for example are immutable and the JVM does all sorts of optimization with them. But you'll also notice that there are special helper classes, StringBuilder and StringBuffer, just to create new Strings. In general, every time you change an immutable field you have to create a new object.

Brain Candy fucked around with this message at 12:05 on Mar 25, 2008

Brain Candy
May 18, 2006

epswing posted:

There are lots of ways...

code:
StringBuilder qry = new StringBuilder();
Iterator accountIds = accounts.keySet().iterator();
while (accountIds.hasNext())
	qry.append("'" + accountIds.next() + "',");
if (qry.charAt(qry.length()-1) == ',')
	qry.deleteCharAt(qry.length()-1)

This makes my brain hurt, or maybe its a coffee deficiency.
code:
qry.append("'" + accountIds.next() + "',");
This still leads to multiple String creation, which you were trying to avoid with the StringBuilder. Go with three appends instead.

code:
if (qry.charAt(qry.length()-1) == ',')
Just check that length is non-zero instead?

Brain Candy
May 18, 2006

epswing posted:

Nope, depends on if qry already has content such as "select ...".

In the code block you gave, you constructed qry inside the block. So if your while loop executes at least once, the last char of qry will be ','.

Brain Candy
May 18, 2006

ColdPie posted:

How "should" I be doing this in Java?

Inheritance and/or enums. Its hard to say exactly without any idea of why you want to use bit flags.

Brain Candy
May 18, 2006

Clanpot Shake posted:

...

code:
int aVal = (int)(a.getTotal() * 100000); 
int bVal = (int)(b.getTotal() * 100000);
The comparator must return an int, and because some of my nodes are close together I need to scale their total to minimize integer approximation errors.

Are you sure this does what you think it does? i.e. (int) (6.99999997 * 10) = 69 but (int) (7.0000001 * 10 ) = 70. For positive numbers, (int) is equivalent to floor, not the nearest integer.

Brain Candy
May 18, 2006

Slimy posted:

In C++, I'd just have the implementation of getArrayListByType() return a pointer to foo and bar, which I could dereference.

Why bother to use a switch at all? Why don't you use a List<List<Message>>?

Brain Candy
May 18, 2006

Since it's static anyway... :
code:
public enum MessageType {
   FOO,BAR;
   
   private final List<Message> messages = new ArrayList<Message>();
}

public void clearMessageArray(MessageType type) {
   type.messsages.clear();
}
:q:

Brain Candy
May 18, 2006

rhag posted:

(concatenate strings with +, while == performs an .equals() ).

BZZZT. == foo is NOT .equals(foo) for Strings

You'd have to use .intern() or something similar for == to consistently work.

Brain Candy
May 18, 2006

yatagan posted:

code:
someStringList.toArray(new String[0]);

Since you know the size after the iteration, why don't you just pass it in instead of making two arrays?

Brain Candy
May 18, 2006

rjmccall posted:

Functions: still a more fundamental tool of abstraction than anonymous classes.

Just put this somewhere in your project. Unfortunately, it's still not bound anywhere in the standard libraries that I know of.

code:
import java.util.Collection;
import java.lang.reflect.Array;

public class Assist {

  @SuppressWarnings("unchecked")
  public static <T> T[] toArray(Collection<? extends T> col, Class<T> cls) {
    T[] array = (T[]) Array.newInstance(cls, col.size()); // unavoidable warning
    int i = 0;
    for (T el : col) array[i++] = el;
    return array;
  }
}

This gives a warning for a reason. If T is also generic, T[] will be of the erased type. Arrays do not play nicely with generics.

Brain Candy
May 18, 2006

rjmccall posted:

Also, I must note that every implementation of Collection.toArray has to do exactly what I'm describing here, uncheckable cast and all.

:ssh: don't use arrays.

Brain Candy
May 18, 2006

Mustach posted:

The whole point of this conversation was that the guy was using an API that wanted an array instead of a collection.

Yes, yes, but if you use arrays enough to require a helper method you've got more problems than making the arrays.

Brain Candy
May 18, 2006

rjmccall posted:

Heaven save us from the vicious tyranny of having too many helper functions.

Way to miss the point!

Brain Candy
May 18, 2006

If only there were some way to hide the interaction with bad code without re-writting it. :rolleye:

Brain Candy
May 18, 2006

Unless you are using large lists (say 20000+), an ArrayList will be faster and allows constant time random access. If you only need to use the Deque interface, why not just use an ArrayDeque? Hell, if you only use List for iteration, just use Collection.

Brain Candy
May 18, 2006

Hmm, that is a little unclear. Second time's the charm : if you only use the List interface for .iterator() you could just store/pass/return things as Collections or Iterables instead.

edit: ^^^ ha, apparently I wasn't completely unintelligible

Brain Candy
May 18, 2006

The problem I see with linked list is that for any non-trivially sized list

code:
for(int i = 0; i < list.size(); ++i)
{
  T t = list.get(i);
  //...
}
performs very differently depending on the type of the list, something I really shouldn't need to know. Granted, my sample should be replaced with for-each, but similar problems come up for set(int, T) and sorting operations.

You can tell that is a design problem by the fact that the Collections API has instanceof checks for a RandomAccess marker interface buried in its guts.

Brain Candy
May 18, 2006

Linked list makes a lot of sense if your insertions are heads or tails, but hey it's a Deque. What I'm saying is that a linked list, despite its name, is crappy as a List.

Brain Candy
May 18, 2006

StickFigs posted:

I need to count the number of comparisons and swaps(aka exchanges) that occur in this code when sorting an int array:

*code*

Where the hell do I put the numSwaps++

Does insertion sort work by swapping?

Homework dude posted:

and numComparison++('s)?

Look for compareTo.

Brain Candy
May 18, 2006

reordered!=swapped

Imagine four balls on the edge of a cliff... insertion sort is the same way.

Brain Candy
May 18, 2006

yatagan posted:

I agree, but this is return !A && !B, which takes me a second to parse.

DeMorgan's laws should be burned into your brain.

Brain Candy
May 18, 2006

Necc0 posted:

I'm just getting into generics in java and I can't figure out how to compare to generic variables.

code:
class TreeNode< E extends Comparable< E> >
{
   ...

   public TreeNode( Comparable<E> nodeData )
   { 
      data = (E) nodeData;              
      leftNode = rightNode = null; // node has no children
   }
...

You can just use E instead of Comparable<E> in your method signature, there is
no need for casting.

code:
class TreeNode< E extends Comparable< E> >
{
   ...

   public TreeNode(E nodeData )
   { 
      data = nodeData;              
      leftNode = rightNode = null; // node has no children
   }
...

Brain Candy
May 18, 2006

Parantumaton posted:

There isn't convention for this which causes people to use at least these three depending on how bad the coffee was the morning they started programming:

Interface starts with I (ICarAnalogy), class name as normal. (CarAnalogy) Quite straight forward, nothing special about it.
Interface is named normally(CarAnalogy), implementation is appended with Impl(CarAnalogyImpl). This, in my opinion, is the ugliest convention. Looks especially horrible if you use common clutter words such as Factory, Processor or Service.
Interface denotes general level of applicability(CarAnalogy), class name denotes specific part of specialized implementation(WhatCarIsToCarpetAnalogy). As you can see from the example, it's very explicit which is good but it will also easily cause quite lengthy and thus horrible class names very easily.

Bad programmer, no biscuit! Hungarian notation is terrible unless you program exclusively in notepad.

Brain Candy
May 18, 2006

Internet Janitor posted:

Don't drive yourself insane trying to get rid of exceptions everywhere, but avoid using them anywhere performance is a significant concern.

Don't use exceptions for flow control and you won't have to worry about performance issues!

Brain Candy
May 18, 2006

An exception is thrown because :

User provides bad data
You log the error. Because you are using I/O this is far slower than a normal operation. You provide feed back to the user.

A programmer was made a mistake
You log the error. Because you are using I/O this is far slower than a normal operation. If the error is fatal, you exit.

Exceptions are being used for flow control or a magical extra return value
If you wrote it, gently caress you. Go stick your head in blender. If you didn't write it, speed is the least of your concerns.

Outside of rare corner cases, who cares if exceptions are slow?

Brain Candy
May 18, 2006

Exceptions in java are for exceptional things. If you want to write things more python-y (StopIteration), you can use labeled breaks :

code:
  butts :
  while( ... ) {
    while ( ...) {
      while ( ... ) {
        while ( ... ) {
          break butts; // jump out of the outermost loop
        }
      }
    }
  }

Brain Candy
May 18, 2006

Internet Janitor posted:

And if you want to break out of deeply nested recursion... basically don't do that.

:ughh: return

Brain Candy
May 18, 2006

poemdexter posted:

code:
int userInput = theirNumber;

if (userInput <= accounts.length) {
do your code
}

Kamakaze9 posted:

code:
for(int k=0; k <= accounts.length; k++)
  if(accnum == accounts[k].getId())
  {more code

It’s been said that there are only two hard problems in Computer Science: cache invalidation, naming things and off-by-one errors

Brain Candy
May 18, 2006

HFX posted:

Where are these callback mechanisms for non blocking i/o. Specifically, is there a way I could use them with stuff from concurrent and maybe show an example / tutorial?

All the tutorials I looked at seemed rather basic. So I ended up doing what I always do in low level languages, and implemented the items to do them myself. Which is painful of course.

Look at http://java.sun.com/developer/technicalArticles/releases/nio/, use the links at the bottom if you need more.

Brain Candy
May 18, 2006

Java 7 fixed some bugs

code:
public class Foo<X extends Foo<X>>
{
  private final int num;

  public boolean compileError(X x)
  {
    return this.num == x.num; //You can't access a private field here! Explosions!
  }

  private int what(Foo<?> foo)
  {
    return foo.num;
  }  

  public boolean totallyOkay(X x)
  {
    return this.num == what(x);
  }
}

Brain Candy
May 18, 2006

List is basically useless as an interface for solving real problems because I have no idea whether random access is going to require iterating through half the list.

Brain Candy
May 18, 2006

HFX posted:

Who cares. The point of an interface is that you don't care about the underlying implementation, and if you do you go look up its instantiation / its behavior should be documented if it matters.

If it is really important because you are doing lots of lookups compared to insertions / traversals, then you define it as ArrayList because in this case you really do care about 0(1) element access.

List (the interface) is is overly broad when I receive it from someone else. I shouldn't have to require an ArrayList, because my method will perform similarly on a any list with constant time element access... like the ones returned from Arrays.toList, or a Collections.unmodifiableList that wraps an ArrayList, let alone user defined ones.

Brain Candy
May 18, 2006

RandomAccess is a marker interface. Hay, I love using instanceof (just like Collections classes are forced to!)

Brain Candy
May 18, 2006

The best comment should have occurred in when making Java 1.2 :

J. Bloch posted:


Re : LinkedList is NOT a List?!?!?

Look guys, just because LinkedList has List in the name doesn't mean it's a List. LinkedList is what we're calling a Queue. Yes, you can use comments to limit the problem with the runtime complexity, but you can't get around the problem of violating LSP; the ultimate caller of any function can be separated by several calls and may not know they are making an error.

Love,
J. Bloch

P.S. Deal with it.

I'm mad, mad about List.

Brain Candy
May 18, 2006

In 2013, multi-threading is important. Please don't corrupt the young with advice based on the terrible enterprisey practices of a decade ago. Your stackholm syndrome is showing.

Brain Candy
May 18, 2006

Interrupts are everywhere 'cause spurious wakes are a real thing.

The key trick is every interruptible call really needs to matched with a loop+condition. If you really want to guarantee a 'sleep' for at least some time :

Java code:
private static void sleep(long millis) {
  long end = System.getCurrentTimeMillis() + millis;  
  long remaining;
  while ( (remaining = end - System.getCurrentTimeMillis()) > 0) {
    try
    {
      Thread.sleep(remaining); //This is sloppy because sleep generally isn't that accurate
    }
    catch (InterruptedException ie){} //Juggernaught, etc.
  }
}
Of course, the super secret sanity preserver is to use Executors in lieu of threads so you can actually cancel/stop things without special handling and let the interrupts work for you.

Brain Candy
May 18, 2006

Looking at it, Guava still has the same problem because it's basically the loop I posted plus actually forwarding the interrupt. The heart of the issue is Thread.sleep(long,long). There are no guarantees about the minimum argument it consistently works for. For years, on windows (maybe still?), Thread.sleep(1) actually slept 10ms because that was the period of the available system timer. This isn't a big deal if you pass 1000ms into it, you've just got to be aware that the accuracy is going to be significantly less than the precision and that it's machine/jvm/os dependent.

Brain Candy
May 18, 2006

You can always put things back into the queue :ssh:

Use LinkedBlockingQueue to have drainTo. Use offer to add things.

edit: there were words about iterators, but you don't need to care

Brain Candy fucked around with this message at 04:40 on Aug 7, 2013

Adbot
ADBOT LOVES YOU

Brain Candy
May 18, 2006

Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply