java - HashMap with StringKey problem? -


I have a list of Fu objects. If a name appears several times, then I have the first item with that name I want to do something

  hashmap & lt; String, foo & gt; Map = new hashmap & lt; String, foo & gt; (); (Foo Bar: this.FooList) {if Map! Pops (bar.getName ()) {map.put (bar.getName (), bar); } And {map.get (bar.getName ()). DoSomeThing (); }}  

But that is not working, because every name (unique or not) is thrown in that map. Is Hashmap not just for reference equality and equality on important items?

This is the required code for you:

  hashmap < String, foo & gt; Map = new hashmap & lt; String, foo & gt; (); (Foo Bar: this.FooList) {if Map! Pops (bar.getName ()) {map.put (bar.getName (), bar); } Else {Foo foo = map.get (bar.getName ()); If (foo! = Null) foo.doSomeThing (); Map.put (bar.getName (), faucet); }}  

A test has been done for this:

  import java.util.HashMap; Import java.util.ArrayList; Example of public squares {public static zero main (string [] args) {new example (). Run (); } Private Arrestist & lt; Foo & gt; FooList = New Arrestist & lt; Foo & gt; (); Public run zero () {FooList.add (New Foo ("ABC", 1)); FooList.add (new Foo ("ABC", 2)); FooList.add (new Foo ("def", 3)); FooList.add (new Foo ("ABC", 4)); FooList.add (new Foo ("ABC", 5)); FooList.add (new foo ("d", 6)); FooList.add (new foo ("def", 7)); Hashmap & lt; String, foo & gt; Map = new hashmap & lt; String, foo & gt; (); (Foo Bar: this.FooList) {if Map! Pops (bar.getName ()) {map.put (bar.getName (), bar); } Else {Foo foo = map.get (bar.getName ()); If (foo! = Null) foo.doSomeThing (); Map.put (bar.getName (), faucet); }}} Class Foo {public Foo (string name, int i) {this.name = name; This.i = i; } Public string getName () {return name; } Public Zero doSomeThing () {System.out.println (getName () + "" + i); } Name of the private string; Private IT; }}  

Output is:

  abc 1 def 3  

Comments

Popular posts from this blog

c# - How to capture HTTP packet with SharpPcap -

php - Multiple Select with Explode: only returns the word "Array" -

php - jQuery AJAX Post not working -