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
trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
I'd like to post that everyone who uses Java to make money should know how both .equals() and .hashCode() work. You can find numerous guides online, plus Joshua Bloch's Effective Java goes into great detail about these methods. I won't get into it here to avoid a huge poo poo post, but here are some links:

http://www.geocities.com/technofundo/tech/java/equalhash.html
http://www.ibm.com/developerworks/java/library/j-jtp05273.html

a good reason why you should know your poo poo:
http://www.hibernate.org/109.html

Also, understand the ramifications of having immutable Strings. A lot of people I've worked with don't understand the concept of immutable Strings and don't know a reason for using StringBuilder other than "you just do." What the gently caress. Also available in numerous online resources or by reading Effective Java.

IntelliJ is really nice. Eclipse is ok if you are willing to put up with its poo poo. Someone likened it to Mac vs PC. If you want something that just works, use IntelliJ, if you like to tinker, go with Eclipse. I haven't used NetBeans enough to say if it's good or bad, all I'm sure of is that Sun is really pushing JRuby so their ruby support is very good.

Adbot
ADBOT LOVES YOU

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

csammis posted:

Can one use IntelliJ or Netbeans if they're developing Java RCP applications that target the Eclipse framework itself, or does that lock one into having to use Eclipse? I'm doing this at work, but I can't friggin' stand Eclipse. It's slower than an rear end in a hat.
Apparantly you can: http://www.jetbrains.com/idea/documentation/usingIDEAforEclipse.html

I don't know how well it'll work, though. It'd be wise to not wipe Eclipse before you try it out for a week or so, despite how tempting it is.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Fly posted:

Most people must readjust their expectations when using fixed precision floating point numbers, such as the IEEE 754 implementation Java has. There are rounding issues because it is impossible to represent some decimal values exactly in such floating point representations.

http://www.ibm.com/developerworks/java/library/j-jtp0114/

You can also try BigDecimal if you don't need balls to the wall arithmetic performance.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
compare should return an int, not a String.

Try:
code:
private class AlphaComparator implements Comparator {
		public int compare(Object obj1, Object obj2) {
			Product prod1 = (Product) obj1;
			Product prod2 = (Product) obj2;
			String name1 = (String) prod1.name;
			String name2 = (String) prod2.name;
			return name1.compareTo(name2);
		}
	}

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

rotor posted:

If I understand you correctly (never a safe bet) it seems that html has nothing do do with this. You have some string data you want formatted nicely on fixed-width font printers, and you're trying to abuse an html layout engine to do this.

My advice would be to look around for something like a java curses library or just write your own - formatters like this are pretty common homework for programming classes, so I'd be surprised if you can't find some kind of libraries floating around.

There is a mature Java curses lib, and it's pretty awesome. A guy at work popped out a tabular pgsql database stats browser with it in a day.

I'm curious why roadheads' implementation has to be in java and not something like LaTeX or PS. Those languages are made for type-setting.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

BELL END posted:

I've never understood the big hullabaloo about this.

Depending on the size of the method, having just one exit point can definitely be helpful.

That said, you shouldn't have monolithic methods that can't fit on a screen if you can help it.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

zootm posted:

Maven's always a point of contention; a lot of people don't like it. I'm not personally a fan myself, I find its behaviour a little too opaque and wide-ranging. It's respected by a lot of other people too, though, it's just a bit of a "love it or hate it" thing.

I'm in the Ant + Ivy camp myself. Maven is really a bitch to get going.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

1337JiveTurkey posted:

In 2002, it'd be talking about Java 1.3 or 1.4 (both are pretty drat old). I wouldn't look at anything which talks about Java before 1.5 except for purposes of maintaining legacy code. Even with legacy code 1.4.2 is as old as I'd venture and I'm hoping to avoid having much to do with my company's clients still stuck on 1.3.1. It's still important to know when certain things came into being or became usable (Ask me about JAXB 1.0), but new code should be predominantly written with the newer versions of the language.


The Sun documentation can be pretty good, although I'm not a fan of their XML/Web Services tutorials and security is just a nightmare regardless. Learning the (very) extensive APIs should probably be one of your first goals. Start out with something simple and sane like java.util.logging and slowly expand your horizons outwards.

I'm curious what that client's excuse for sticking with Java 1.3 is. Did they use some Sun internal API that got removed?

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

epswing posted:

Sounds like this will create a new StringBuilder instance per iteration, in which case the extra append calls would be better.
Why would the compiler do that?

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

epswing posted:

I don't know anything about the java compiler. From my lofty perch, far from such low-level details, it sounds like
code:
String s1 = "hello" + "there";
conceptually amounts to something like
code:
String s1;
StringBuilder sb = new StringBuilder();
sb.append("hello");
sb.append("there");
s1 = sb.toString();
Are there StringBuilder instances lying around that the VM uses on a per-thread basis for all String + String concat operations? I'm interested to know how this works.

I just decompiled this code (All code generated using JDK6_u3, should probably upgrade):

code:
public class StringDemo {
        public static void main(String [] args) {
                String s1 = "Hello" + " world!";
                System.out.println(s1);
        }
}
and javac turned "Hello" + " world!" into a single literal. So, I modified it to this:

code:
public class StringDemo {
        public static void main(String [] args) {
                String s1 = "Hello";
                String s2 =  " ";
                String s3 = " world!";
                String s4 = s1 + s2 + s3;
                System.out.println(s4);
        }
}
and it uses .append() with only 1 instance of StringBuilder.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

epswing posted:

That's exactly what I was concerned with: does the following mean 5 instances of StringBuilder?

Sure does.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

epswing posted:

Ok, which brings me back to http://forums.somethingawful.com/showthread.php?threadid=2780384&pagenumber=5#post342041228



Looks like it would. In which case I'm saying that N*3 calls to append might be faster than N new StringBuilder objects.

Yeah, I misread your post. I actually copied that code straight now and disassembled it and it's definitely creating 2 new StringBuilder instances for every loop. I wonder if HotSpot would be able to optimize this further and move the allocation if it unrolled the loop.

This bugged the poo poo out of me so I benchmarked it. You're right, the overhead of allocating those StringBuilders is significant for even modest numbers of iterations. I'll post the code if anyone wants, but for 1000 keys of random size, it took anywhere from 875-1000ms to run the naive method, and from 0-3ms for the explicit append() method.

I run under linux so the JVM uses the server VM by default. I tried this under -client and got FAR worse performance for the naive method, even after HotSpot dealt with it.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

epswing posted:

I'd love to see it firsthand. :)

code:
import java.util.*;
import java.io.*;

public class StringDemo {

        private static String testNaive(Map<String,String> map) {
                long start = System.currentTimeMillis();
                String qry ="";
                Iterator accountIds = map.keySet().iterator();
                while (accountIds.hasNext()) {
                        qry += "'"+accountIds.next()+"'";
                        if (accountIds.hasNext()) qry+=",";
                }
                System.out.println((System.currentTimeMillis()-start) + "ms for naive.");
                return qry;
        }

        private static String testExplicit(Map<String,String> map) {
                long start = System.currentTimeMillis();
                StringBuilder qry = new StringBuilder();
                Iterator accountIds = map.keySet().iterator();
                while (accountIds.hasNext()) {
                        qry.append("'").append(accountIds.next()).append("'");
                        if (accountIds.hasNext()) qry.append(",");
                }
                System.out.println((System.currentTimeMillis()-start) + "ms for explicit.");
                return qry.toString();
        }

        static Random r = new Random(System.currentTimeMillis());

        private static Map<String,String> generate() {
                int length = 1000;

                Map<String,String> map = new HashMap<String,String>(length);

                byte [] k; byte [] v;

                while (length-- > 0) {
                        int klen = r.nextInt(256);
                        int vlen = r.nextInt(256);
                        k=new byte[klen];
                        v=new byte[vlen];
                        r.nextBytes(k); r.nextBytes(v);
                        map.put(new String(k), new String(v));
                }

                return map;
        }

        private static void write(String name, String data) throws Exception {
                FileWriter f = new FileWriter(name);
                f.write(data,0,data.length());
                f.close();
        }

        public static void main(String [] args) throws Exception {

            Map<String, String> map = generate();

            for (int x = 1; x<100; x++) {
                write("naive.out", testNaive(map));
                write("explicit.out", testExplicit(map));
            }

            System.out.println(map.size() + " pairs");
        }
}
The file writing was just to make sure they were generating the same output. I md5summed the output and it is indeed the same. There's a few optimizations that could be made to the loop itself but that's not what I am testing so I didn't do it.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Brain Candy posted:

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

Yeah, please let us know a bit more about your problem. There is almost always a more elegant way of handling that sort of multiplexing.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
^^ You need to look up the javax.script.Bindings class. That is how you pass variables back and forth between a script and the host java program.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

adante posted:

:confused: sorry, but can you give me a concrete example of what you mean? As far as I can tell getting the Bindings will allow me to get a java reference to the javascript object - but I already do this using the jsEngine.get("foo"). What I want to know is how do I manipulate it? For instance, how would I get a value given a key, or list the keys?

Bindings implements Map, so you'll be able to iterate over the entries just like Map:

code:
for (Map.Entry<String,Object> e:bindings) {
...do stuff...
}
.get() and .put() both work just like Map as well.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Leehro posted:

Coming from a C/C++ background on pointers and references, that was a very helpful discussion. I was always suspicious of java's magic when it comes to passing around objects.

My question relates to the garbage collection in the example. How would you get rid of the point object entirely? just by setting pnt = null in the main method?

The VM will mark it collectible after its containing block's scope ends unless it's referenced somewhere else currently in scope or static, like a Map or a List of some kind. Note that it's just marked for collection, the actual collection happens at some other point.

Like you said, you can set it to null manually and call System.gc(); but absolutely no guarantees are made about when the memory consumed by that class will be reclaimed, if ever.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

hey wiz posted:

Let me see if I'm on the same page with you

key : this you are getting correctly.
type: this should be as simple as value.getClass().getName()
value: this is where you are stuck.

If you were working on simple classes such as String, Boolean, Double as you mentioned in the example, you could just print value.toString(). However, it seems like you are trying to print the value of Objects that don't have a friendly toString() method. These objects may still have a method which will print exactly what you want, but for each class it would be different. If this was the case, how would you determine which method to call on which class to print what you want?

I think I get his point now. There's no good way to get the entries from the internal JS map in the Java host.

I hosed with this in Groovy because it allows for much easier class introspection, and you can basically call .get() thusly:

code:
import javax.script.*

def js = "var m = {1:'a', 2:'b', 3:'c', 'z':26, 'y':24, 'x':23};"
def se = new ScriptEngineManager().getEngineByExtension("js")

se.eval(js)

def m = se.get("m")

println m.get(1,m)
println m.get('z',m)
It'll print pretty much what you expect.

The problem comes when you try to do this poo poo in Java, because you can't even import sun.org.mozilla.javascript.internal.ScriptableObject, at least not with my JDK. You could probably get rhino and cast to whatever ScriptableObject Rhino provides and get() from there. It's a mess and you might want to write a wrapper class for it that implements Map, because honestly this is pretty worthless as it is.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

triplekungfu posted:

setTimeout is a bit weird, I believe it always executes in global scope or something to that effect. Someone else can probably give you a proper explanation.

setTimeout()/setInterval() can take a closure as well as a string:

code:
<html><head><script type="text/javascript">
function doit() {
   var x = 11;
   
   setInterval(function(){ document.getElementById('foo').innerHTML=x++; }, 500);
}

doit();
</script>
<body>
<div id="foo">blah</div>
</body>
</html>

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
^ goddamn you

clayburn posted:

It looks like I have another problem with my HashMap involving collisions. Looking at my data set, I know for a fact that collisions are happening, and this is causing problems for me. Every time that I search for a value at a specific key, I only get one of the values, where sometimes I may want the other value. For example, if "foo" and "bar" are stored at the same key, I will only ever get "foo" even though sometimes I may want to find any string that is not "foo." Is there any way to go about this? I have read the API entry for HashMaps over and over and cannot seem to find a solution to this.

So wait, are you trying to store multiple objects under the same key?

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

clayburn posted:

Yes, and I'm starting to get the impression that it was a really bad idea. I thought that it would simply handle that as a collision and store the object somewhere else that would still be accessible.

If you want to store multiple items under a unique hash, you should make the value a Collection:

code:
Map<K,Collection<V>> 
It makes insertion and deletion a bit more complicated but it's nothing unmanagable. However, it seems you might want to reevaluate your algorithm, based on the way you're talking.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

zootm posted:

The Commons Collections (I link to collections15 since it's the "generic" version) contains a MultiMap collection type for these sorts of semantics.


Well I'll be goddamned. It must be a side effect of working in an environment devoid of intellectual curiosity but I never even bothered to check Commons for something like this. Thanks.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
FYI, the JVM has no such restriction on overloaded return types. Only the JLS does. You can do this in Jaskell and possilby Scala, IIRC.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

zootm posted:

I'm fairly sure you cannot do this in Scala, for what it's worth. I'll have a look tonight if I remember though.

Also the fact that you can do it in Jaskell does not mean that the bytecode or the JVM supports it directly. A lot of JVM languages encode such concepts (the multiple inheritance in Scala, for example, is not something that JVM bytecode supports directly).

I understand what you mean, but the JVM docs specifically state that it does not restrict overloaded method returns.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

zootm posted:

Cool, just checking. Is that how Jaskell works? It seems strange to have a JVM language that Java can't call.

I actually do not know how Jaskell is implemented. I kinda wrote that post quickly and should have put the word "also" in there somewhere. :p

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

zootm posted:

Sorry I don't want to seem like I'm digging in at you, I'm just interested!

Heh, it's cool. Jaskell is open source, you can always take a look ;)

I've honsetly spent most of my "programmer education time" following Groovy, since it interfaces so well with Java. And learning Haskell as well as I can, but that's a bit off-topic.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Alan Greenspan posted:

Is there an easy way to put breakpoints on Java library functions? Let's say I want to put a breakpoint on one of the constructors of java.io.File.

IDE is Eclipse but I'm willing to switch to any IDE for this.

Yeah, in Eclipse your java source should already be linked to the rt.jar file. Just ctrl+click on a new File() statement and it'll take you right to the constructor. If that doesn't work, you probably have to link the source. I can tell you how to do that if you need.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Alan Greenspan posted:

Thanks for the reply but apparently this is tricky because when I set a breakpoint into the rt.jar source ...

:saddowns:

What versions of Eclipse and Java are you running?

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

ColdPie posted:

This should be super easy, but I'm just having a dog of a time figuring this out.

Java doesn't have unsigned types, which makes reading binary files from languages that do have unsigned types a pain. I'm using a java.nio.ByteBuffer to read a file, and need to do a conversion from an unsigned byte into a Java type (I figure just an int). I've got b = b < 0 ? b + 256 : b;, which seems like an obvious fix, except if b=128. In that case, the binary reads 1000 0000, which when converted to signed types is -0, which fails that test and returns 0 instead of 128 like it should.

I feel like I'm overthinking this. What am I missing?

You want to do bitwise and'ing on it and store it in a type that is larger than necesary. In your example, you want to put those bytes in an int after you & 0xFF them to yank the sign extension.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
IntelliJ has the most mature Groovy and Grails plugins available, from what I've been able to tell. I write most of my Groovy in vim so I'm pretty much ignorant beyond what I can read online.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Flamadiddle posted:

Yeah, I figured as much. I'm new to Java anyway, and so far have had to learn HTTP pushes and JDBC connections. I guess I'll need to learn about opening socket connections and such?

This is pretty much exactly what web services are meant to do. Secure, abstracted, simple (for various values of simple).

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

1337JiveTurkey posted:

If it's some practice toy app for fun running on a local network, there's nothing wrong with just opening a socket to the server and passing serialized objects for messages.

I agree. Maybe I misunderstood but he used the word "staff" so I figured this would be production.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
Do you need the radix? I wrote this in like 10s and it works well:

code:
  1 public class B {
  2     public static void main(String [] args) {
  3         System.out.println(revConvert(new int [] {0x00, 0x60, 0xff, 0xff}));
  4     }
  5
  6
  7     public static int revConvert(int[] array) {
  8         int ret = 0;
  9         for(int i = array.length - 1; i >= 0; i--) {
 10             ret = ret << 8;
 11             ret += array[i];
 12         }
 13         return ret;
 14     }
 15 }

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

Boz0r posted:

I don't really know, actually. I guess it doesn't really matter, but my problem right now is, if I use the method TRex EaterofCars wrote before with {00, 60, ff, ff} and {0, 96, -1, -1} I get two different results, with the {0, 96, -1, -1} result being wrong.

Yes because -1 is represented as 0xffffffff, bit shifting with that number will obviously produce wrong results. Try this instead:
code:
  7     public static int revConvert(int[] array) {
  8         int ret = 0;
  9         for(int i = array.length - 1; i >= 0; i--) {
 10             ret = ret << 8;
 11             ret |= array[i] & 0xff;
 12         }
 13         return ret;
 14     }

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

rjmccall posted:

Copy and paste, do some ridiculously inefficient things with reflection, or switch programming languages. Sorry.

If you can use the Apache Commons Collection library, they have a method in CollectionUtils called reverseArray.

http://commons.apache.org/collections/index.html

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

pogothemonkey0 posted:

This is difficult to explain, so bear with me.

I will be comparing two strings, each of varying length, and storing the comparison value to be looked up later. I need to know how to store these comparisons.

If I have already compared the strings "SH" and "SO," I need to look up the value in my data structure. I need a two dimensional structure where I can say, "I need the value at the index of SH and SO." I have no idea what structure can do that. An array wont work because the index is an int.

Any ideas?

I'd personally just use a HashMap and depending on the amount of comparisons, I'd maybe make a Map<String, Map <String, Integer>> so a map that holds a map of strings to comparisons. That said, bookkeeping would be a pain in the rear end unless you know the order of string comparisons would remain the same.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

LakeMalcom posted:

just use a hashmap with the strings concatenated as your key? if order matters, then roll your own little map to put and get the reverse order string.

code:
Map<String, Object> map = new HashMap<String,Object>();
map.put(str1+str2, value);

Concatenation is dangerous because you can end up with collisions.

What I was suggesting is a map system like this (in Groovy syntax cause I'm lazy):
code:
[cat:[rat:1, dog:2]] 
There's no reason 'cat' would be overwritten nor should any data be lost. You have access to all of cat's comparisons. So I guess I don't see the issue... unless I don't understand what you're saying.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

pearofducks posted:

Quick concurrency question (I'm new to threads). I've got a homemade generic linked list, most of the operations on it take place inside a loop, and only one operation actually uses the list. So I'm wondering if its possible to have the linked list operation run in its own thread, and the loop to keep going. I've read up on it some and it seems like it just provides the ability to override the run method, but I'd like to have any of the linked list actions be in their own thread. Is this possible? If so can someone just give me a brief idea of what to do?

Why'd you roll your own linked list when the JDK provides you with one (java.util.LinkedList) that has built-in concurrency support (using the Collections class) already?

That said, you probably could do what you want to do but you're being pretty vague about what "operations" and "actions" you need to perform. Can you be a little more precise?

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.
Without putting to fine a point on it, you will have tremendous problems if you think that you'll have "enough time" to modify a list before some other thread can access it.

To answer your question, check out the synchronized keyword and the Collections.synchronizedList() method, if you implement List then that will basically solve it for you. Also, there are a few books on Java concurrency that are pretty good: specifically Java Concurrency in Practice and Concurrent Programming in Java: Design Principles and Patterns if you are interested.

Concurrency is frighteningly difficult to do correctly, especially with some of Java's more quirky semantics and rules involving synchronization.

Adbot
ADBOT LOVES YOU

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

triplekungfu posted:

Yep, in one of my earlier classes we could lose up to 20% per assignment for incorrect formatting, and every class except the earliest couple would dock marks for missing or poor javadoc.

I had a drat S/390 Assembler professor knock of 67% of an assignment because of lack of comments. That might sound acceptable until I mention that the uncommented lines were printlines. Goddamn that guy.

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