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
Max Facetime
Apr 18, 2009

Also, the solution 27^5 + 84^5 + 110^5 + 133^5 = 144^5 is a hint to the algorithm.

Adbot
ADBOT LOVES YOU

mister_gosh
May 24, 2002

I'm new to Java 5+

What's going on in this code, what is the colon character and classname after it?

code:
public class Address : Entity
Edit: Crap...I think I'm looking at C# code snippets, aren't I? :)

mister_gosh fucked around with this message at 20:00 on Feb 2, 2010

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
That's C#.

karuna
Oct 3, 2006
How can I iterate over Keys in a LinkedHashMap?

Will this work for looping through the keys in fileMap, will record be given the first value of fileMap?

LinkedHashMap<String, Integer> fileMap;

//String is key/value, Integer is frequency

code:

String record = null;
for(Map.Entry<String, Integer> entry : fileMap.entrySet()){
			record = entry.getKey();
			
}
I've also seen this code for iterating over values but can I change it to Iterate over a key which is a string??

code:

Collection<Integer> c = fileMap.values()

//obtain an Iterator for Collection		
Iterator itr = c.iterator();
//iterate through LinkedHashMap values iterator
		
while(itr.hasNext())
   System.out.println(itr.next());

maskenfreiheit
Dec 30, 2004
...

maskenfreiheit fucked around with this message at 03:45 on Sep 29, 2010

Flamadiddle
May 9, 2004

Check your PMs

Fly
Nov 3, 2002

moral compass

GregNorc posted:


A:1 B:1 C:1 D:2 E: 1

A:1 B:1 C:2 D:1 E: 1

... I think you get the drift
These are effectively the same condition, and it's pointless to duplicate effort that way. You only need to check permutations and not combinations. You can generate the possible combinations of a, b, c, and d from the permutations once you have them.

lewi
Sep 3, 2006
King

GregNorc posted:

lots of useless code

How about realising the conditions that e has to be larger than max(a,b,c,d) and smaller than (2^63)^0.2 if you're using longs. I'm sure that gives you a suitable starting point.

lewi fucked around with this message at 00:11 on Feb 3, 2010

OddObserver
Apr 3, 2009

lewi posted:

How about realising the conditions that e has to be larger than max(a,b,c,d) and smaller than (2^63)^0.2 if you're using longs. I'm sure that gives you a suitable starting point.

Is there even any need to iterate e?

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
gregnorc: here is a basic lesson on nesting loops.

A For loop like the following:

code:
for(int a = 0; a < 5; a++) {
  print(a);
}
can be rewritten using a While loop to make it a little more clear what happens when:

code:
int a = 0;
while(a < 5) {
  print(a);
  a++;
}
First, a is declared and initialized. Then, we check that a is less than 5, which is true, so we print a, increment a and check again. Eventually, a will be >= 5, at which point we break out of the loop and a falls out of scope.

Looking at a For loop again, we can identify four parts:

quote:

for( A; B; C) {
D
}

A - the initializer. An expression evaluated before the loop executes.
B - the precondition. An expression that controls when the loop terminates (loop while this is true, break when false)
C - the postoperation. An expression evaluated after every iteration of a loop.
D - the body, a series of statements making up the content of a loop.

you can make the precondition more complex:

code:
boolean flag = true;
for(int a = 0; ((a < 5)&&(flag)); a++) {
   // more stuff in here
}
you can step by numbers other than 1:

code:
for(int a = 0; a < 5; a += 2) {
  // more stuff in here
}
you can put another loop in the body section:

code:
for(int a = 0; a < 5; a++) {
  // a is in scope here
  for(int b = 0; b < 5; b++) {
    // both a and b are in scope here
    print(a+":"+b);
  }
  // b has fallen out of scope
}
Try executing something like this code (better yet, by hand), and see what happens.

I highly recommend you pretend the break and continue keywords don't exist until you've mastered these ideas.

Volguus
Mar 3, 2009

karuna posted:

How can I iterate over Keys in a LinkedHashMap?

Will this work for looping through the keys in fileMap, will record be given the first value of fileMap?

LinkedHashMap<String, Integer> fileMap;

//String is key/value, Integer is frequency

code:

String record = null;
for(Map.Entry<String, Integer> entry : fileMap.entrySet()){
			record = entry.getKey();
			
}
I've also seen this code for iterating over values but can I change it to Iterate over a key which is a string??

code:

Collection<Integer> c = fileMap.values()

//obtain an Iterator for Collection		
Iterator itr = c.iterator();
//iterate through LinkedHashMap values iterator
		
while(itr.hasNext())
   System.out.println(itr.next());

To iterate over the keys of a Map (any kind of a class that implements the Map interface: HashMap, LinkedHashMap,Hashtable,etc.), do this:

code:
Set<K> keys=map.keySet();
for(K k: keys){
 V value=map.get(k);
}
For your case, you would have:
code:
Set<String> keys=fileMap.keySet();
for(String key:keys){
 Integer val=fileMap.get(key);
}

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

rhag posted:

To iterate over the keys of a Map (any kind of a class that implements the Map interface: HashMap, LinkedHashMap,Hashtable,etc.), do this:

code:
Set<K> keys=map.keySet();
for(K k: keys){
 V value=map.get(k);
}
For your case, you would have:
code:
Set<String> keys=fileMap.keySet();
for(String key:keys){
 Integer val=fileMap.get(key);
}

I believe it's technically faster to iterate over the entry set if you need both key and value in your block.

code:
for (Map.Entry<String, Integer> e:fileMap.entrySet()) {
    String k = e.getKey();
    Integer v = e.getValue();
}

zootm
Aug 8, 2006

We used to be better friends.

TRex EaterofCars posted:

I believe it's technically faster to iterate over the entry set if you need both key and value in your block.
Yeah, it avoids doing an extra lookup on the map each iteration.

epswing
Nov 4, 2003

Soiled Meat
Assuming "lookup" means retrieving a value based on a key, does Map.Entry magically obtain a value without a lookup?

epswing fucked around with this message at 17:39 on Feb 4, 2010

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
There doesn't have to be anything magical about it; it's up to the implementation of the interface. But do you really care? If you want the set of (key, value) pairs of a Map, entrySet() gives you exactly what you want. Using keySet() and then calling get() repeatedly is at-best reimplementing the same functionality.

Fly
Nov 3, 2002

moral compass

epswing posted:

Assuming "lookup" means retrieving a value based on a key, does Map.Entry magically obtain a value without a lookup?
When iterating over a HashMap's entrySet, there is no hash lookup done at all. The entry objects contain the key and value references so retrieving the key and value are simple accessor methods on the Entry object.

Parantumaton
Jan 29, 2009


The OnLy ThInG
i LoVe MoRe
ThAn ChUgGiNg SeMeN
iS gEtTiNg PaId To Be A
sOcIaL MeDiA sHiLl
FoR mIcRoSoFt
AnD nOkIa

Fly posted:

When iterating over a HashMap's entrySet, there is no hash lookup done at all. The entry objects contain the key and value references so retrieving the key and value are simple accessor methods on the Entry object.

One gotcha I'd like to mention, Entry contains apparently only weak references to the key and value it holds so the following code may throw NPE if you get a bit unlucky with GC:

code:
Entry<Key, Value> selectedEntry;

for(Entry<Key, Value> entry : someMap.entrySet()) {
	if (entry.getKey().equals(somethingOrRather)) {
		selectedEntry = entry;
		break;
	}
}
if (selectedEntry != null) {
	selectedEntry.getValue().doThings(); // woop, NPE may get thrown here
}
This is, of course, a slight horror code-wise but who knows, maybe someone is thinking of doing this to use the Key and Value multiple times after finding the correct entry pair.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Parantumaton posted:

One gotcha I'd like to mention, Entry contains apparently only weak references to the key and value it holds so the following code may throw NPE if you get a bit unlucky with GC:

This is the first I've ever heard of these, how interesting.
http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html

Fly
Nov 3, 2002

moral compass

Parantumaton posted:

One gotcha I'd like to mention, Entry contains apparently only weak references to the key and value it holds...
This is only true for WeakHashMap and not HashMap, but the programmer should generally not depend on either one being in use. The HashMap.Entry class uses regular strong references to hold both the key and value:
code:
// java.util.HashMap.java (JDK 1.6.0_10)
    static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        final int hash;
The WeakHashMap.Entry class uses a WeakReference only for the key:
code:
// java.util.WeakHashMap.java (JDK 1.6.0_10)
    private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> {
        private V value;
        private final int hash;
        private Entry<K,V> next;
It is just as possible that a key would become null within the loop as well:
code:
for(Entry<Key, Value> entry : someMap.entrySet()) {
    // getKey() may be null already, so this is not safe.
    if (entry.getKey().equals(somethingOrRather)) {
        // getKey() may be null now if it was not already.
        doSomething(entry.getKey());
        break;
    }
}
If you may be using a WeakHashMap I think you have to watch out in any case because entry.getKey() might begin returning null at any point.

Coredump
Dec 1, 2002

Alright, I'm a total Java retard so please bare with me. I found a snippet of code online that I was feeding in different input to see what I could make it do and I've run into a wall of sorts. I don't know java well enough to describe what I want to do without showing the code so here it goes.

code:
public class ArraytoString{
 
  public static String arrayToString2(String[] a, String separator) {
    StringBuffer result = new StringBuffer();
    if (a.length > 0) {
        result.append(a[0]);
        for (int i=1; i<a.length; i++) {
            result.append(separator);
            result.append(a[i]);
        }
    }
    return result.toString();
 }
  
public static void main(String[] args)
{
   String[] toppings = {"chicken", "bacon", "ham"};
   System.out.println(arrayToString2(toppings, ","));
}
}
That works. It takes the array toppings and puts it into a string separated by commas. Looks like this:
code:
chicken,bacon,ham
However if try to use the line:
code:
System.out.println(arrayToString2({"chicken", "bacon", "ham"}, ","));
I get an illegal start of expression error. WHHHYYY???

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"

Coredump posted:

However if try to use the line:
code:
System.out.println(arrayToString2({"chicken", "bacon", "ham"}, ","));
I get an illegal start of expression error. WHHHYYY???

Try this:
code:
System.out.println(arrayToString2(new String[] {"chicken", "bacon", "ham"}, ","));
The String[] toppings = { ... } syntax is only valid when you're initializing the contents of the array at the same time you're declaring the variable. In your example above, you want to initialize an "anonymous array", which in Java is done by putting new ElementType[] before the array items in braces.

edit:grammars

Flobbster fucked around with this message at 23:30 on Feb 7, 2010

epswing
Nov 4, 2003

Soiled Meat
That was actually an interview question I gave recently, just to weed out the liars. Turns out about half couldn't do it. And about half of the ones that did couldn't do my next question, which was "same thing, recursively."

karuna
Oct 3, 2006
I have a LinkedList<ArrayList<String>>.

I need to write it out to a text file.
Each ArrayList is one line.
I need to insert a separator between each element in the ArrayList.

i.e

ArrayList [1,2,3,4,5,6]

Should be (if the separator is say "-") "1-2-3-4-5-6"

What would be the most efficent way to acheive this?
Really not liking having to keep creating new Strings seen as they are not mutable.

code:
               FileWriter fstream = new FileWriter("M://Docs/testResult.txt");
	       BufferedWriter out = new BufferedWriter(fstream);
	       
	       ListIterator<ArrayList<String>> itr = dataset.listIterator();
	       while(itr.hasNext()){
	    	   
	    	   String temp = "";
	    	   ArrayList<String> fileOutput = dataset.removeFirst();

                   temp = temp + fileOutput(fileOutput.size() - 1) + "-";
	    	
	    	   out.write(temp);
	       }

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
If I understand the question right, shouldn't you be able to do something like this?

code:
FileWriter fstream = new FileWriter("M://Docs/testResult.txt");
BufferedWriter out = new BufferedWriter(fstream);

for(ArrayList<String> list : dataset) {
  for(String str : list) {
    out.write(str);
    out.write("-");
  }
  out.write('\n');
}
obviously, this will leave a trailing '-', but that's an easy fix left as an exercise to the reader. Attaching a PrintWriter to that BufferedWriter might make things easier.

Contra Duck
Nov 4, 2004

#1 DAD

karuna posted:

What would be the most efficent way to acheive this?
Really not liking having to keep creating new Strings seen as they are not mutable.

Not going to answer the question as Internet Janitor already did a fine job of that, but for future reference you might want to check out the StringBuilder class. That lets you concatenate lots of Strings together without the overhead of creating a new String object for each intermediate step. Interestingly, the '+' operator on a String is just shorthand for using a StringBuilder, so a piece of code like 'string1 + string2 + string3' will actually compile to something like 'new StringBuilder(string1).append(string2).append(string3).toString()'.

e: There's also StringBuffer too which does the exact same thing but is threadsafe if that's important to you.

Contra Duck fucked around with this message at 11:52 on Feb 8, 2010

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

Contra Duck posted:

Not going to answer the question as Internet Janitor already did a fine job of that, but for future reference you might want to check out the StringBuilder class. That lets you concatenate lots of Strings together without the overhead of creating a new String object for each intermediate step. Interestingly, the '+' operator on a String is just shorthand for using a StringBuilder, so a piece of code like 'string1 + string2 + string3' will actually compile to something like 'new StringBuilder(string1).append(string2).append(string3).toString()'.

e: There's also StringBuffer too which does the exact same thing but is threadsafe if that's important to you.

Be careful with assuming + always converts to StringBuilder. There are circumstances where javac will not do that. Sadly, I'm lazy and I don't know offhand what those circumstances are but know that they exist.

When in doubt, javap your classes.

Volguus
Mar 3, 2009

TRex EaterofCars posted:

Be careful with assuming + always converts to StringBuilder. There are circumstances where javac will not do that. Sadly, I'm lazy and I don't know offhand what those circumstances are but know that they exist.

When in doubt, javap your classes.

The circumstances are: at least JDK 1.5 from Sun :). (Mainly because that's when StringBuilder appeared).
Any other JDK, or earlier versions do not do that.
As such, since one shouldn't really rely on new compiler features, and since writing the proper code is so easy, I would recommend just using StringBuilder to concatenate strings in a loop.

Since 1.5 (I think) the javac (from Sun, no idea about other vendors), got a bunch of features that make life easier, but confuse the hell out of new programmers. For example, == with strings on both sides translates into .equals(). Newcomers to java may think that's true for objects as well (that's why, never use == unless you really want to compare instances, otherwise just use .equals).
Autoboxing : there doesn't seem to be any difference between int and Integer now. I imagine that's helluva confusing for a newcomer.

I love the new features introduced then, as they do make life easier, but new people who don't carefully read the documentation and just want to write Hello World as fast as possible won't even notice the subtle differences between operators on String and MyShinyObject.

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

rhag posted:

For example, == with strings on both sides translates into .equals().
What
code:
§ javac -version
javac 1.6.0_16
code:
§ cat Equals.java
public class Equals{
        public static boolean operator(String a, String b){
                return a == b;
        }

        public static boolean method(String a, String b){
                return a.equals(b);
        }

        public static void main(String[] args){
                String s1 = "hello", s2 = "world";
                if(operator(s1, s2) != method(s1, s2)) System.exit(1);
        }
}
code:
§ javap -c Equals
...

public static boolean operator(java.lang.String, java.lang.String);
  Code:
   0:   aload_0
   1:   aload_1
   2:   if_acmpne       9
   5:   iconst_1
   6:   goto    10
   9:   iconst_0
   10:  ireturn

public static boolean method(java.lang.String, java.lang.String);
  Code:
   0:   aload_0
   1:   aload_1
   2:   invokevirtual   #2; //Method java/lang/String.equals:(Ljava/lang/Object;)Z
   5:   ireturn

...

Volguus
Mar 3, 2009

Mustach posted:

What
code:
§ javac -version
javac 1.6.0_16
code:
§ cat Equals.java
public class Equals{
        public static boolean operator(String a, String b){
                return a == b;
        }

        public static boolean method(String a, String b){
                return a.equals(b);
        }

        public static void main(String[] args){
                String s1 = "hello", s2 = "world";
                if(operator(s1, s2) != method(s1, s2)) System.exit(1);
        }
}
code:
§ javap -c Equals
...

public static boolean operator(java.lang.String, java.lang.String);
  Code:
   0:   aload_0
   1:   aload_1
   2:   if_acmpne       9
   5:   iconst_1
   6:   goto    10
   9:   iconst_0
   10:  ireturn

public static boolean method(java.lang.String, java.lang.String);
  Code:
   0:   aload_0
   1:   aload_1
   2:   invokevirtual   #2; //Method java/lang/String.equals:(Ljava/lang/Object;)Z
   5:   ireturn

...

Well, yes, its not really equals, since it maintains a static hashtable of strings, but it certainly behaves the same way.
that is:
code:
  String s1 = "hello", s2 = "hello";
  s1==s2 //true
though it shouldn't (it doesn't create 2 objects there, but it looks like it is).

edit:
The entire idea here is how confusing is this for newcomers: do you have 2 instances there or don't you? If you don't, when why when I do MyShinyObject x=new MyShinyObject()3 times, I end up with 3 instances (thus == doesnt work).
Most (certainly not all) won't read the Java language specification before they write their first hello world. Nor will they look at the generated code.

Volguus fucked around with this message at 17:23 on Feb 8, 2010

OddObserver
Apr 3, 2009

rhag posted:

Well, yes, its not really equals, since it maintains a static hashtable of strings, but it certainly behaves the same way.
that is:
code:
  String s1 = "hello", s2 = "hello";
  s1==s2 //true
though it shouldn't (it doesn't create 2 objects there, but it looks like it is).

It either should or can (the language spec is vague, IIRC), and not because it's replacing == with .equals, but exactly because it's not creating redundant string objects.

"a" + "b" == "ab" either can or should return true, too.

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

rhag posted:

it certainly behaves the same way
code:
§ cat Input.java
public class Input{
        public static void main(String[] args){
                String s = "go";
                java.util.Scanner sc = new java.util.Scanner(System.in);
                while(sc.hasNext()){
                        String f = sc.next().trim();
                        if(s == f) System.out.println("Right");
                        else System.out.println("Wrong");
                }
        }
}
code:
§ yes go | java Input
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
...

Mustach fucked around with this message at 17:38 on Feb 8, 2010

Volguus
Mar 3, 2009

Mustach posted:

code:
§ cat Input.java
public class Input{
        public static void main(String[] args){
                String s = "go";
                java.util.Scanner sc = new java.util.Scanner(System.in);
                while(sc.hasNext()){
                        String f = sc.next().trim();
                        if(s == f) System.out.println("Right");
                        else System.out.println("Wrong");
                }
        }
}
code:
§ yes go | java Input
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
Wrong
...

I'm sorry sir, but your code is a completely different story.
Reading strings from streams is a different ball game on many levels. I know you just want to prove me wrong for the sake of it, but your example doesn't really cut it.
If you read a string from system.in (or anywhere else, as an input from something) is pretty logical that it will create a new object in memory.

RitualConfuser
Apr 22, 2008

rhag posted:

Autoboxing : there doesn't seem to be any difference between int and Integer now. I imagine that's helluva confusing for a newcomer.

== may have some unexpected behavior since the values in [-128,127] are cached:
code:
    Integer a = 100;
    Integer b = 100;

    Integer c = 200;
    Integer d = 200;
        
    System.out.println(a == b);
    System.out.println(c == d);
code:
true
false
From the Sun JDK 1.5 Integer class:
code:
    public static Integer valueOf(int i) {
	final int offset = 128;
	if (i >= -128 && i <= 127) { // must cache 
	    return IntegerCache.cache[i + offset];
	}
        return new Integer(i);
    }
So, as already pointed out several times, use the equals method when comparing objects.

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

rhag posted:

I'm sorry sir, but your code is a completely different story.
Reading strings from streams is a different ball game on many levels. I know you just want to prove me wrong for the sake of it, but your example doesn't really cut it.
I want to show how you're wrong because everything you've said on the subject has been either incorrect or misinformative.

"== translates to .equals()."
"Oh, well I didn't realllyyyyyy mean the .equals() method, it just behaves the same way."
"A program reading input? Fool, this whole time I was only referring to string literals, mwahahahahaha"

Fly
Nov 3, 2002

moral compass

RitualConfuser posted:

So, as already pointed out several times, use the equals method when comparing objects.
I recommend findbugs for newbies and veterans alike. It will point out possible bugs like this and explain them. For experienced programmers it helps by catching some accidental things in the code.

Parantumaton
Jan 29, 2009


The OnLy ThInG
i LoVe MoRe
ThAn ChUgGiNg SeMeN
iS gEtTiNg PaId To Be A
sOcIaL MeDiA sHiLl
FoR mIcRoSoFt
AnD nOkIa
Are you discussing of interned Strings as being converted to .equals() comparison on the fly?

Fly
Nov 3, 2002

moral compass

Parantumaton posted:

Are you discussing of interned Strings as being converted to .equals() comparison on the fly?
Something similar. Interned Strings are not handled differently by .equals(). Instead, because interning gives a reference to the same object, the == operator works. Small Integer references returned from Integer.valueOf() are a shared in a similar way.

zootm
Aug 8, 2006

We used to be better friends.
Summary of the String.equals() thing:

s1 == s2 is never equivalent to s1.equals( s2 )[1] and treating it as such is both dangerous and wrong.

Let's see use-cases for using == with String objects:
  • You have some genuine need to check they are the same instance. Outside of unit tests, this is extremely unusual. Inside unit tests, it's merely very unusual.
  • You are testing literals against literals. You should almost definitely be using enums instead. I'd be interested to see a situation where that is not the case.
  • You are testing two values which are guaranteed to be intern()ed. This is generally dangerous and involves putting the strings into an in-memory map potentially permanently. You should only do this if the set is guaranteed to be small, enums are not a good fit, you have a genuine need to test the values a huge number of times, and you have already identified that String comparisons are your bottleneck.

In conclusion: don't do it, don't tell people to do it.

[1] (or the nullsafe equivalent of the same)

Fly
Nov 3, 2002

moral compass

zootm posted:

s1 == s2 is never equivalent to s1.equals( s2 )[1] and treating it as such is both dangerous and wrong.
[1] (or the nullsafe equivalent of the same)
Truth.

Regarding Enums, I do not remember reading docs or code that would indicate a deserialized Enum would have the same reference as it did before. Do you have any reference to whether Enums are interned somehow upon deserialization?

It looks like deserialization does create Enums as the same reference (http://java.sun.com/j2se/1.5.0/docs/guide/serialization/spec/serial-arch.html#6469):

code:
import java.io.*;

public class Foo
{
	enum Bar { A, B };

	public static void main(final String[] argv) throws Exception
	{
		final Bar a = Bar.A;
		final ByteArrayOutputStream baos = new ByteArrayOutputStream();
		final ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(a);

		final Bar b = (Bar)
			new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))
			.readObject();

		System.out.println("a == b ? " + (a == b));
	}
}
$ java Foo
a == b ? true

Fly fucked around with this message at 20:28 on Feb 9, 2010

Adbot
ADBOT LOVES YOU

zootm
Aug 8, 2006

We used to be better friends.

Fly posted:

Regarding Enums, I do not remember reading docs or code that would indicate a deserialized Enum would have the same reference as it did before. Do you have any reference to whether Enums are interned somehow upon deserialization?
The "singleton" property of enum values is preserved on (de)serialization by its implementation being unusually implemented, as described on this page:

quote:

The rules for serializing an enum instance differ from those for serializing an "ordinary" serializable object: the serialized form of an enum instance consists only of its enum constant name, along with information identifying its base enum type. Deserialization behavior differs as well--the class information is used to find the appropriate enum class, and the Enum.valueOf method is called with that class and the received constant name in order to obtain the enum constant to return.

A lot of thought seems to have gone into making enums "work right". I guess there's a chance it might be possible to circumvent this using reflection, but even that seems unlikely.

e: f, b

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