Is it possible to add two separate arrays into one hash set?

Recommended Answers

All 6 Replies

How do I go about making it though....I've tried:

h2.addAll(numbers);
h2.addAll(numbers2);

//Give me just the values from numbers2

and

h2.add(numbers);
h2.add(numbers2);

//which gives an error on the "add" portion of the code

and

h2.add(numbers,numbers2);

//which gives an error on the "add" portion of the code

Any ideas?

Are you wanting to add the two arrays as two elements, or are you wanting to add all the elements in the arrays?
For the first case

int[] a = {1,2,3};
    int[] b = {4,5};
    HashSet h = new HashSet();
    h.add(a);
    h.add(b);
    for (Object o : h) System.out.println(o);
    // prints two array objects

for the second

int[] a = {1,2,3};
    int[] b = {4,5};
    HashSet h = new HashSet();    
    for (int i : a) h.add(i);
    for (int i : b) h.add(i);   
    for (Object o : h) System.out.println(o);
    // prints 1 .. 5

Why is it that when I use my arrays in place of the "a" or "b" in the example, I only come out with the values in array b?

public void AddNumbers()
		{   
			HashSet<Integer> h = new HashSet<Integer>();    
			for (int i : numbers) h.add(i);
			for (int i : numbers2) h.add(i);   
			for (Object o : h) System.out.println(o);
		}

Output:

Please Enter 5 variables (First Set): 
Please enter value in slot 0:1
Please enter value in slot 1:2
Please enter value in slot 2:3
Please enter value in slot 3:4
Please enter value in slot 4:5
ArrayList Values Are: [1, 2, 3, 4, 5]

Please Enter 5 variables (2nd Set): 
Please enter value in slot 0:6
Please enter value in slot 1:7
Please enter value in slot 2:8
Please enter value in slot 3:9
Please enter value in slot 4:10
ArrayList Values Are: [1, 2, 3, 4, 5]/n
Adjusted numbers1: [1, 2, 3, 4, 5]
Adjusted numbers2: [6, 7, 8, 9, 10]
6
7
8
9
10

Loo at your arraylist output in lines 8 and 16. It looks like you are putting the wrong numbers in your arrays somehow?
Anyway, that little code snippet is OK - so the problem lies somewhere else. Do you want to post more of the code?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.