Seshu Vinay
Seshu Vinay

Reputation: 13588

Copy array without redundancy

I have two arrays in my program. One is full(with redundant items in it). I want to copy all the items to the second empty array without redundancy. The only problem I have is "how to declare size of the second array?" Because Iam not sure how many are the redundant items in the first array.

Upvotes: 0

Views: 331

Answers (6)

Petr Mensik
Petr Mensik

Reputation: 27496

I would use Set for this, that will remove duplicates from your array and you convert then back to array or another collection of you need that.

Set<Item> withoutDups = new HashSet<Item>(Arrays.asList(yourArray));
//now you have it without duplicates and do whatevet you want with it:-)
Item[] arrayWithoutDups = new Item[withoutDups.size()];
withoutDups.toArray(arrayWithoutDups); // fill the array

Upvotes: 5

Raghunandan
Raghunandan

Reputation: 133560

Convert string array to list. Use a LinkedHashSet to eliminate duplicates. The LinkedHashSet maintains insertion order along with uniqueness.

Edit: I have removed the List as it is redundant.

    String[] words = {"ace", "ace","boom", "crew", "dog", "eon"}; 
    Set<String> hs = new LinkedHashSet<String>(Arrays.asList(words));
    String[]  mywords=hs.toArray(new String[hs.size()]);
    for(int i=0;i<mywords.length;i++)
    {
        System.out.println("..."+mywords[i]);
    }

Upvotes: 2

mki
mki

Reputation: 635

Since you don't know which item are redundant you need to loop over your array. I suggest that you use temporary List uniqueItemsList to add the items during your loop. The list will grow as needed.

Then you can get a array with code like this (replace String with your type) :

String uniqueItems[] = new String[uniqueItemsList.size()]; 
uniqueItems = uniqueItemsList.toArray(uniqueItems);

Upvotes: -1

Igor Konoplyanko
Igor Konoplyanko

Reputation: 9374

So what's the problem ? Loop through values in source array, find number of redundant items. Then allocate second array and in next loop copy values.

Complexity of this approach is 2n=O(n)

Upvotes: 0

mishadoff
mishadoff

Reputation: 10789

Use ArrayList which size can be smaller than original array, then create array from it, if needed.

Upvotes: 1

Ali
Ali

Reputation: 1409

Arrays are of fixed size. You should use ArrayList in this case.

However, if you have to use an array then you should allocate the size of 2nd array equal to the size of 1st array because it may contain no redundant elements at all.

Upvotes: 1

Related Questions