-6

Is it possible to make an array of an array? What I am trying to do is basically make a an array of another array without duplicates.

For example:

String[] colour ={"blue","blue","red","blue","red","red","orange","yellow","purple","green","blue"};

and then make a new array from String[] colour into:

String[] uniqueColour = {"blue","red","orange","yellow","purple","green"}

using a function and without just declaring it? Cause lets say I change all the values of String[] Colour and turn it into

String[] Fruits = {"Apple","Banana","Orange","Tomato","Apple","Banana"}

then without doing or changing anything else the function should create

String[] uniqueColour ={"Apple","Banana","Orange","Tomato"}

Does such a thing exist? Sorry for the trouble. And I'm new to java as well.

A thank you to anyone who can contribute or help me out.

EDIT: Okay so by using this: - Thanks to Doorknob's answer

Set<String> uniqueSet = new HashSet<String>(Arrays.asList(colour));
String[] uniqueColours = uniqueSet.toArray(new String[0]);

how would I then try to display it as:

Blue
Red
Yellow
Green
Purple
ect

instead of [Blue,Red,Yellow,Green,Purple,etc]

Leo
  • 1
  • 1
  • 1
  • 3
  • "*then without doing or changing anything else the function should create*" - Then how do you think things are changed? – Maroun Apr 18 '13 at 12:13
  • *Is it possible to make an array of an array?* Yes , but what are you trying to achieve is very vague ! – AllTooSir Apr 18 '13 at 12:13
  • 1
    When we say "array of arrays" we mean a two-dimensional array -- an array where each element is another array. You seem to be asking about removing duplicates, so your wording is quite confusing. – Nathaniel Waisbrot Apr 18 '13 at 12:15
  • Oh I'm sorry guys I am terrible at explaining things I'll edit it. – Leo Apr 18 '13 at 12:18

1 Answers1

1

Use a Set to remove duplicates:

Set<String> uniqueSet = new HashSet<String>(Arrays.asList(colour));
String[] uniqueColours = uniqueSet.toArray(new String[0]);

To display it in the way you wanted:

for (String s : uniqueColors) System.out.println(s);
tckmn
  • 57,719
  • 27
  • 114
  • 156
  • How would I display the String[] Unique Colours? By that I mean instead of it showing up as [blue,red,orange,yellow,purple,green] I want to display it as `Blue\nRed\nOrange\nYellow\nPurple\nGreen` – Leo Apr 18 '13 at 12:21
  • @Leo Why the unaccept? Did it not work? – tckmn Apr 18 '13 at 12:49
  • @Leo Is there anything wrong with this solution? – tckmn Apr 21 '13 at 22:20