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
csammis
Aug 26, 2003

Mental Institution
This, this right here, is why schools that don't teach C/C++/[pointers] any more are causing Problems :colbert:

Adbot
ADBOT LOVES YOU

ShinAli
May 2, 2003

The Kid better watch his step.
That or they should explain what passing by reference actually does :(

I guess I should feel fortunate that a lot of Java schools probably don't even touch on that. Oh well, I'm going into SEGFAULT territory this coming fall :v:

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
When my kids start learning how to use objects I go out of my to explain this to them. But yeah I don't think the Deitel book even offers an explanation.

Leehro
Feb 20, 2003

"It's a gaming ship."
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?

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.

hey wiz
Jun 18, 2005

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

adante posted:

code:
 key :       type       :  value
   x : java.lang.Double : 1.0
   y : java.lang.String : hello
   z : java.lang.Boolean : false
key : this you are getting correctly.
type: this should be as simple as value.getClass().getName()
value: this is where you are stuck.

adante posted:

code:
key: context	value: javax.script.SimpleScriptContext@b23210
key: foo	value: [object Object]
key: print	value: sun.org.mozilla.javascript.internal.InterpretedFunction@f4f44a
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?

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.

adante
Sep 18, 2003

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.
Actually I cannot get the key or list of keys either (maybe you can, if so please share how :dance: ).

hey wiz posted:

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?
the output I made is so that I could (hopefully) get a program that is a simple proof of concept to show how to access get the keys/values in the object. I don't actually want to print those variables.

As to how to figure out the type and so forth of the values - well I will deal with that after I figure out how to get the values :). As I understand it js is basically variable/object/functions anyway - variables map to string/bool/double, and if I figure out how to manipulate objects (1st part of the problem) then that is solved, which leaves functions to deal with.

TRex EaterofCars posted:

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.

Unfortunately you cannot cast it (or I cannot figure out how to):

code:
        js.eval("var asdf = {a:1, b:'asdf', c:false};");
        Object aaa = js.get("asdf");
        org.mozilla.javascript.NativeObject s = org.mozilla.javascript.NativeObject)aaa;
will throw a ClassCastException. Same thing happens if you cast to a omj.ScriptableObject :bang:

TRex EaterofCars posted:

groovy
wow, I had no idea this existed. Very cool, but unfortunately switching to another language is probably overkill at the moment :)

zootm
Aug 8, 2006

We used to be better friends.

TRex EaterofCars posted:

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.
The mark actually occurs separately as well, but this is basically it. In general just make sure you're not referring to an object you don't want any more and the JVM will do the right thing.

TRex EaterofCars posted:

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.
I don't think setting it null even guarantees the JVM will be able to see that it's unreachable. In general one should never, ever rely on stuff like that. Also I don't think System.gc() is guaranteed to do anything, it's just a "hint" which is only useful for debugging, if that.

adante posted:

Actually I cannot get the key or list of keys either (maybe you can, if so please share how :dance: ).
Have you tried just attaching a debugger and introspecting the object using that?

LightI3ulb
Oct 28, 2006

Standard pleasure model.
I hata Java. Can someone explain to me why Java keeps spitting out:
code:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at Whiteboard.<init>(Whiteboard.java:16)
	at Whiteboard.createAndShowGUI(Whiteboard.java:82)
	at Whiteboard.access$0(Whiteboard.java:75)
	at Whiteboard$1.run(Whiteboard.java:21)
	at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
with

code:
import javax.swing.*;

import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

public class Whiteboard extends JPanel implements MouseListener {
	Drawspace drawSpace;
	JTextArea textArea;
	Graphics2D g = (Graphics2D) drawSpace.getGraphics();

	public static void main(String[] args) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		});
    	}

    public Whiteboard() {
        super(new GridBagLayout());
        GridBagLayout gridbag = (GridBagLayout)getLayout();
        GridBagConstraints c = new GridBagConstraints();

        c.fill = GridBagConstraints.VERTICAL;
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.weightx = 1.0;
        c.weighty = 1.0;

        c.insets = new Insets(1, 1, 1, 1);
        drawSpace = new Drawspace(new Color(0.98f, 0.97f, 0.85f));
	c.anchor = GridBagConstraints.NORTHWEST;
        gridbag.setConstraints(drawSpace, c);
        add(drawSpace);

	JButton drawRectangle = new JButton("Rectangle");
	drawRectangle.setHorizontalAlignment(JButton.RIGHT);
	add(drawRectangle);


        setPreferredSize(new Dimension(450, 450));
        setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
	}
	
	public void mousePressed(MouseEvent e) {
			g.drawLine((e.getX()), (e.getY()), ((e.getX())+1), ((e.getY())+1));
			g.dispose();
	}
	
	public void mouseReleased(MouseEvent e) {
	
	}
	
	public void mouseEntered(MouseEvent e) {
	
	}
	
	public void mouseExited(MouseEvent e) {
	
	}
	
	public void mouseClicked(MouseEvent e) {
		g.drawLine((e.getX()), (e.getY()), ((e.getX())+1), ((e.getY())+1));
		g.dispose();
	}

    

    private static void createAndShowGUI() {
        JFrame.setDefaultLookAndFeelDecorated(true);

        JFrame frame = new JFrame("Whiteboard");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   
        JComponent newContentPane = new Whiteboard();
        newContentPane.setOpaque(true);
        frame.setContentPane(newContentPane);

   
        frame.pack();
        frame.setVisible(true);
    }
}
code:
import javax.swing.*;
import java.awt.Dimension;
import java.awt.Color;

public class Drawspace extends JLabel {
    Dimension minSize = new Dimension(100, 100);

    public Drawspace(Color color) {
        setBackground(color);
        setOpaque(true);
        setBorder(BorderFactory.createLineBorder(Color.black));
    }

    public Dimension getMinimumSize() {
        return minSize;
    }

    public Dimension getPreferredSize() {
        return minSize;
    }
} 

ynef
Jun 12, 2002
Row 16 in the file that the JVM complains about says: "Graphics2D g = (Graphics2D) drawSpace.getGraphics();" -- at that point, however, drawSpace is not initialized to anything and is therefore null.

GameCube
Nov 21, 2006

Anybody here know a good guide to using Derby/JavaDB? I've been following instructions to the t, yet I still can't connect to my friggin' database.

ShinAli
May 2, 2003

The Kid better watch his step.

ynef posted:

Row 16 in the file that the JVM complains about says: "Graphics2D g = (Graphics2D) drawSpace.getGraphics();" -- at that point, however, drawSpace is not initialized to anything and is therefore null.

This. A tip to spot these kind of problems right away is using a debugger in Eclipse or NetBeans. They both will display all visible variables and indicate their value, which makes "NullPointerException" easier to deal with on multi statement line of code.

standard
Jan 1, 2005
magic

ShinAli posted:

This. A tip to spot these kind of problems right away is using a debugger in Eclipse or NetBeans. They both will display all visible variables and indicate their value, which makes "NullPointerException" easier to deal with on multi statement line of code.

A further tip:
In eclipse there is a button in the breakpoints pane to add breakpoints when exceptions occur.
Add one to java.lang.NullPointerException

clayburn
Mar 6, 2007

Cammy Cam Juice
I have a question about the HashMap class. I have populated a HashMap with a simple object I have created, basically consisting of two strings. One of these strings holds a segment of text from a file, the other holds the file name. What I want to do is to use the HashMap.contains method to determine if a particular string matches any of the text segments, and then use whatever get method is in the class to determine the file name. I figured that overriding the hashcode method would do the trick; I defined the hashcode method of the class to return the hashcode value of the string that we will be searching for. Apparently, this doesn't quite do the job. I am fairly new to hash tables, so if anyone could give me a few tips it would be very appreciated.

Incoherence
May 22, 2004

POYO AND TEAR

clayburn posted:

I have a question about the HashMap class. I have populated a HashMap with a simple object I have created, basically consisting of two strings. One of these strings holds a segment of text from a file, the other holds the file name. What I want to do is to use the HashMap.contains method to determine if a particular string matches any of the text segments, and then use whatever get method is in the class to determine the file name. I figured that overriding the hashcode method would do the trick; I defined the hashcode method of the class to return the hashcode value of the string that we will be searching for. Apparently, this doesn't quite do the job. I am fairly new to hash tables, so if anyone could give me a few tips it would be very appreciated.
1. First rule of hashCode(): if two objects have the same hashCode(), equals() should return true on them as well. The converse is usually the part people trip over (overriding equals() but not hashCode()). I'm not sure you keep that invariant, which you should do.

2. You're not being exactly clear on what you're doing. What it sounds like is that you're building an index and searching it, so your hash map looks like this:
"foo" -> "file1.txt"
"bar" -> "file2.txt"
"baz" -> "file3.txt"
"cat" -> "file1.txt"
and your search term is "foo". In this case, the strings should be the keys, and the filenames should be the values, and contains() will do what you want. But it sounds like either (a) the strings aren't the keys (what is, then?), (b) you're actually using HashSet instead of HashMap (you want HashMap), or (c) this is not what you mean at all, at which point you should clarify.

clayburn
Mar 6, 2007

Cammy Cam Juice
I had a nice long post typed up and lost it due to the forum maintenance. Basically I asked if this code:
code:
hashMap hm = new hashMap();
hm.put("foo", "file1.txt");
if(hm.containsKey("foo")
{
      String fileName = hm.get("foo");
}
would evaluate the if statement's condition to true and have fileName reference the string "file1.txt." If that would work then I think I understand it now.

edit: This works perfectly, even better than I had hoped it would. Thanks for the help.

clayburn fucked around with this message at 04:51 on Apr 22, 2008

syphon^2
Sep 22, 2004
I hope Javascript questions are welcome here. There's no "Javascript Megathread", and this question is very very simple, so I didn't want to start a new thread just for it.

I'm very new to Javascript (Perl's my language of choice), but I'm writing a web-app using Perl's CGI::Ajax, which enables Ajax by mapping Javascript functions on your web page to Perl functions.

Anyhoo, the Javascript functions need to have their parameters sorted in a particular way for CGI::Ajax. I'm having problems with this... so I'm hoping you guys can help me.
code:
var scalar = 'foo';
var array = ['yabba','dabba','doo'];

//does not work!
functionToInvoke( [scalar,array], ['ouput_div'] );

//kinda works, but only feeds in the first element of the array
functionToInvoke( [scalar,array[0]], ['ouput_div'] );

//yay!
functionToInvoke( [scalar,'yabba','dabba','doo'], ['ouput_div'] );
As you can see, functionToInvoke requires 2 arguments to work. A list of parameters to feed into the Perl function, and a div (or list of divs) to put the output into.

In my example, I need to feed the following list of parameters into the Perl function - ['foo','yabba','dabba','doo']. Hard coding all the values works fine, or even hard coding a specific array element works. However, just providing the array (with the hope that it'd just iterate through each value) doesn't work. It's hard to tell exactly what it's feeding into functionToInvoke(), but it looks like it's trying to feed the index and then element.

Any ideas?

EDIT: Just a bit more information... I tried
code:
alert(scalar,array);
and it output "foo,yabba,dabba,doo" (pretty much exactly what I want). I'm not sure why the alert function is parsing it this way, but the CGI::Ajax function is not.

syphon^2 fucked around with this message at 15:30 on Apr 22, 2008

Fehler
Dec 14, 2004

.
You might be looking for the concat() method. Try something like this:

code:
var a = new Array(scalar); //create new array for scalar
a = a.concat(array); //append array

functionToInvoke(a, ['ouput_div'] );

syphon^2
Sep 22, 2004

Fehler posted:

You might be looking for the concat() method. Try something like this:

code:
var a = new Array(scalar); //create new array for scalar
a = a.concat(array); //append array

functionToInvoke(a, ['ouput_div'] );
That worked! Thanks!

How come alert seemed to display my data properly, but when supplying it in the same manner for functionToInvoke, it failed? Maybe something to do with how CGI::Ajax works?

epswing
Nov 4, 2003

Soiled Meat
Regarding hashCode and equals, it's really important that java developers read and understand this: http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf

e: fixed link

epswing fucked around with this message at 15:46 on Apr 22, 2008

Fehler
Dec 14, 2004

.

syphon^2 posted:

That worked! Thanks!

How come alert seemed to display my data properly, but when supplying it in the same manner for functionToInvoke, it failed? Maybe something to do with how CGI::Ajax works?
I think alert() just can't display multidimensional arrays properly, so [1, [2, 3]] would look like [1, 2, 3].

tef
May 30, 2004

-> some l-system crap ->

syphon^2 posted:

I hope Javascript questions are welcome here. There's no "Javascript Megathread", and this question is very very simple, so I didn't want to start a new thread just for it.

For future reference - the web dev and the general programming questions thread might be better. JavaScript and Java really only have the name in common.

syphon^2
Sep 22, 2004
EDIT: ^^^^^ Duly noted (right on the heels of another post). Thanks for the tip. :)

Another javascript question...

I'm trying to use setInterval() and setTimeout() to create a basic timer. I want my page to run doIt() every 10 seconds for 30 minutes, and then stop. (although I have the times cut down drastically for testing purposes)
code:
function autoDoIt() {
	//do it every 2 seconds
	var intervalID = setInterval( "doIt();", 2000 ); 
	//set a timeout, so that after 10 seconds, the 'intervalID' loop is terminated.
	setTimeout('clearInterval(intervalID)',10000);
}
The interval gets set properly... and doIt() is run every 2 seconds as it should. However, after 10 seconds, I simply get an error "'intervalID' is not defined", and doIt() keeps getting run... forever.

Note that if I change
code:
setTimeout('clearInterval(intervalID)',10000);
to
code:
clearInterval(intervalID);
Everything works great (although my interval is terminated before it ever gets a chance to do anything).

This seems like a pretty simple use-case. What am I doing wrong?

Fehler
Dec 14, 2004

.
Try making intervalID global, i.e. add "var intervalID;" at the top outside the function.

syphon^2
Sep 22, 2004

Fehler posted:

Try making intervalID global, i.e. add "var intervalID;" at the top outside the function.

Awesome... that seems to have done the trick!

One last time... before I stop pestering you java gurus with js questions... why did this happen? I mean, obviously having intervalID as an argument within an argument brought it out of scope from where it was declared... but why would it do that?

Also, how can I reference the intervalID scoped inside the autoDoIt() function? Given the layout of my .js file... I really really want to avoid having a single random global floating around there. :)

the onion wizard
Apr 14, 2004

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.

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>

poopiehead
Oct 6, 2004

Incoherence posted:

1. First rule of hashCode(): if two objects have the same hashCode(), equals() should return true on them as well. The converse is usually the part people trip over (overriding equals() but not hashCode()). I'm not sure you keep that invariant, which you should do.

Unless I'm reading this wrong, you got it backwards.

This is a valid, but stupid implementation of a hashcode.
code:
int hashcode()
{
  return 0;
}
if a.equals(b) the a.hashcode() should == b.hashcode()

logically equivalent but put in a different way:

if a.hashcode() != b.hashcode() then a.equals(b) should be false.

Incoherence
May 22, 2004

POYO AND TEAR

poopiehead posted:

Unless I'm reading this wrong, you got it backwards.

This is a valid, but stupid implementation of a hashcode.
code:
int hashcode()
{
  return 0;
}
if a.equals(b) the a.hashcode() should == b.hashcode()

logically equivalent but put in a different way:

if a.hashcode() != b.hashcode() then a.equals(b) should be false.
I didn't get it backwards (both directions are equally true), but I should have been more clear about that being an if-and-only-if statement:

If you override either hashCode() or equals(), you should override both such that
a.hashCode() == b.hashCode() iff a.equals(b) (and b.equals(a))

poopiehead
Oct 6, 2004

Incoherence posted:

I didn't get it backwards (both directions are equally true), but I should have been more clear about that being an if-and-only-if statement:

If you override either hashCode() or equals(), you should override both such that
a.hashCode() == b.hashCode() iff a.equals(b) (and b.equals(a))

Sorry. That't not correct though. Multiple values can have the same hash code. You want to minimize collisions, but they will happen.

These are both valid hash functions but wouldn't be if a.hashcode()==b.hashcode() -> a.equals(b)

return 0; \\1.hashcode() == 2.hashcode but 1 != 2
return x % 35; \\ 1.hashcode() == 36.hashcode() but 36 != 1

java posted:


public int hashCode()

Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

The general contract of hashCode is:

* Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
* If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
* It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

poopiehead fucked around with this message at 03:54 on Apr 23, 2008

Incoherence
May 22, 2004

POYO AND TEAR

poopiehead posted:

Sorry. That't not correct though. Multiple values can have the same hash code. You want to minimize collisions, but they will happen.
Yeah, you're right. I'll go back to my fantasy land of collision-less hashes now...

quote:

These are both valid hash functions but wouldn't be if a.hashcode()==b.hashcode() -> a.equals(b)

return 0; \\1.hashcode() == 2.hashcode but 1 != 2
return x % 35; \\ 1.hashcode() == 36.hashcode() but 36 != 1
"Valid", but you could do better in either case.

clayburn
Mar 6, 2007

Cammy Cam Juice
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.

oh no computer
May 27, 2003

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.
I was under the impression that HashMaps don't allow more than one value to be stored with the same key, each subsequent call to put(k) overwrites what is already at k.

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?

clayburn
Mar 6, 2007

Cammy Cam Juice
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.

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.

zootm
Aug 8, 2006

We used to be better friends.

BELL END posted:

I was under the impression that HashMaps don't allow more than one value to be stored with the same key, each subsequent call to put(k) overwrites what is already at k.
Yep. From the Javadoc:

quote:

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for this key, the old value is replaced by the specified value.
The Commons Collections (I link to collections15 since it's the "generic" version) contains a MultiMap collection type for these sorts of semantics.

Edit: Also TRex's suggestion is the "traditional" way of doing this, and will work if you don't want to pull a JAR dependency. It's just a little bit more work to deal with the collection yourself.

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.

Adbot
ADBOT LOVES YOU

zootm
Aug 8, 2006

We used to be better friends.

TRex EaterofCars posted:

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.
It's one of those things that you don't usually find out about until someone you're working with starts using it :)

Glad it's helped you too :)

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