import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
public class Main
{
public static void main(String[] args) {
Set numbers=new HashSet();
numbers.add(new Integer(45));
numbers.add(88);
numbers.add(new Integer(77));
numbers.add(null);
numbers.add(789L);
Iterator iterator=numbers.iterator();
while(iterator.hasNext())
System.out.print(iterator.next());
}
}
Asked
Active
Viewed 52 times
-2
shark
- 1
- 2
-
What's more important to you: ordering or fast lookup/insertion/deletion? – ndc85430 Jun 02 '22 at 07:26
-
1Use a LinkedHashSet for keeping ordering... – NoDataFound Jun 02 '22 at 07:36
-
"how we gonna determine the output when we iterate over below program?" - you read it, it's printed out on the console. – daniu Jun 02 '22 at 07:41
-
null789884577 is the output, need to understand why null is priority in order of printing – shark Jun 02 '22 at 08:05
-
1What’s the point of using `new Integer(…)` here? Is the line `numbers.add(88);` indicates. you already know that you can simply write the number. Further, there’s no need to deal with an `Iterator`; you can simply write `for(Object o: numbers) System.out.print(o);` to print all elements. And no, `null` doesn’t have priority. Just try `Set – Holger Jun 02 '22 at 08:44
-
Thanks Holger for the response. Actually it's my assignment question. Just wondering about the output .. because in which order they are coming on the console – shark Jun 02 '22 at 09:51
-
2The order is intentionally unspecified. In practice, it depends on several implementation details. 1) the hashcode provided by the object 2) transformation(s) applied by the map implementation and substitutes, i.e. `null` is usually mapped to zero 3) the projection into an array location (depends on the current capacity) 4) within a single array location either, insertion order, hash code order, or natural order of the keys. See [this answer](https://stackoverflow.com/a/45575607/2711488) for some details. – Holger Jun 02 '22 at 10:12