12 Replies - 9480 Views - Last Post: 04 February 2012 - 12:38 PM Rate Topic: -----

#1 smithjr5  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 23
  • Joined: 04-February 12

Identify and display duplicate elements in an array using an iterator

Posted 04 February 2012 - 01:00 AM

I am having trouble identifing and diplaying the duplicate elements in the array using the iterator. I commented on the section I am having trouble on. I am trying to generate a number of random integers with a ceiling. Show the duplicate integers. Prompt the user if they want to delete them. Sort the integers and display Max/Min.

I figured out how to output the Max/Min, sort, prompt to delete duplicates, but I can't for the life of me identify the duplicates. While trying to reuse the delete duplicate code to show the duplicates I get errors.

Is there something that I am doing slightly wrong or extremely wrong?

V/r

import java.util.*;      //**all the Collections Framework classes are here
import javax.swing.*;

public class ArrayListTest {
    public static void main(String[] args) {
	String input, userstring;
	int size;
	int range;
	int randInt;
	int userAnswer;

        //**indexed list of (any kind of) objects (but not primitives).
        //**size expands as needed
	ArrayList myArrayList = new ArrayList();

	input = JOptionPane.showInputDialog( "Enter number of random ints to generate" );
	size = Integer.parseInt( input );

	input = JOptionPane.showInputDialog( "Enter upper range of the random ints" );
	range = Integer.parseInt( input );

	for (int i=1; i<=size; i++) {   //i is not an index, just a loop counter
	    randInt = (int)(Math.random()*range);  //random int between 0 and range-1
	    //uncomment if this code confuses you:
	    //System.out.println("generated int: " + randInt);
	    myArrayList.add(new Integer(randInt));  //**must wrap int into Integer
	}

	//**iterate over all the objects in the arraylist collection.
	Iterator it=myArrayList.iterator();
	//**an iterator is for accessing all the objects of collection, one by one.
	//**hasNext() is true until reach end of the collection.
	//**next()  returns the next object in the iteration.
	//**notice no for loop looping over indexes!
	System.out.println("Here are your random integers: ");
	while (it.hasNext())
	    //display them on one line, separated by a blank
	    System.out.print(it.next() + " ");
	System.out.println();


	//Used to Identify and Display duplicate integers

        // This is where I am having trouble displaying duplicate elements.  What am I doing wrong???
	Collections.sort(myArrayList);
        it=myArrayList.iterator();
        while (it.hasNext())
	    if (it(i)) == (it(i-1))) {
		System.out.print();
		}








	//Used to prompt user if they want to delete the duplicate integers
	userAnswer = JOptionPane.showConfirmDialog(null,
						   "Do you want to delete duplicate integers in your list?",
						   "Delete 'em?",
						   JOptionPane.YES_NO_OPTION);
	if (userAnswer == JOptionPane.YES_OPTION) {
	 Collections.sort(myArrayList);
            it=myArrayList.iterator();
	Set uniqueEntries = new HashSet();
        for (int i=1; i<=size; i++) {
            Object element = it.next();
            if (!uniqueEntries.add(element)) // if current element is a duplicate,
            it.remove();                 // remove it
    	    }
	}

        //** sort

        Collections.sort(myArrayList);
        it=myArrayList.iterator();
	System.out.println();
	System.out.println("Here are your sorted integers: ");
	while (it.hasNext())
	    System.out.print(it.next() + " ");
	System.out.println();

	//** smallest and largest values
        System.out.println("Min value in arraylist: " + Collections.min(myArrayList));
        System.out.println("Max value in arraylist: " + Collections.max(myArrayList));


    }
}


This post has been edited by blackcompe: 04 February 2012 - 01:31 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Identify and display duplicate elements in an array using an iterator

#2 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1155
  • View blog
  • Posts: 2,536
  • Joined: 05-May 05

Re: Identify and display duplicate elements in an array using an iterator

Posted 04 February 2012 - 01:22 AM

What is this code you posted? Do you have a question?
Was This Post Helpful? 0
  • +
  • -

#3 smithjr5  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 23
  • Joined: 04-February 12

Re: Identify and display duplicate elements in an array using an iterator

Posted 04 February 2012 - 01:36 AM

This is what I came up with now


	//Used to Identify and Display duplicate integers
	Collections.sort(myArrayList);
        it=myArrayList.iterator();
	Set duplicateEntries = new HashSet();
        for (int i=1; i<=size; i++) {
            Object element = it.next();
            if (!duplicateEntries.add(element)) // if current element is a duplicate,
            System.out.println(it);                 // Output Element
    	    }



When I run it it get a weird output

java.util.ArrayList$Itr@1417690
java.util.ArrayList$Itr@1417690
java.util.ArrayList$Itr@1417690
java.util.ArrayList$Itr@1417690
java.util.ArrayList$Itr@1417690
Was This Post Helpful? 0
  • +
  • -

#4 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1155
  • View blog
  • Posts: 2,536
  • Joined: 05-May 05

Re: Identify and display duplicate elements in an array using an iterator

Posted 04 February 2012 - 01:52 AM

If you must use an iterator, traverse the list of elements in a loop, saving the index of the current element. Inside that loop, enter a nested loop where you'll traverse the list again (from the beginning), this time skipping the saved index. Compare the current element to every element in nested loop. If you find two that are the same, they are duplicates.

FOR i = 0 to list_end
     VAR curr_elem = list[i]
     VAR curr_index = i
     FOR j = 0 to list_end
           IF j != curr_index AND curr_elem == list[j]
                 PRINT curr_elem + "is a duplicate"
     END FOR
END FOR



You can adjust that to use iterators.

Quote

This is what I came up with now


That works.

Quote

When I run it it get a weird output


Iterators don't override Object.toString, so you won't get a meaningful representation. Why aren't you printing the element?
Was This Post Helpful? 0
  • +
  • -

#5 smithjr5  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 23
  • Joined: 04-February 12

Re: Identify and display duplicate elements in an array using an iterator

Posted 04 February 2012 - 02:17 AM

for (int i=1; i<=size; i++) {
    Object element = it.next()
        if (!duplicateEntries.add(element)) // if current element is a duplicate,
            System.out.println(it);         // Output Element

        }



I thought that when I did the System.out.printtln(it);

It would print the element to a new line

This post has been edited by Atli: 04 February 2012 - 06:03 AM
Reason for edit:: Added [code] tags and removed the duplicate.

Was This Post Helpful? 0
  • +
  • -

#6 smithjr5  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 23
  • Joined: 04-February 12

Re: Identify and display duplicate elements in an array using an iterator

Posted 04 February 2012 - 03:37 AM

Hello,
I have a program that creates and displays random integers. It then identifies and prompts the user if they want to delete the duplicates from the array.
The code compiles fine, works fine if there are no duplicates, but picks up some random ones when there are duplicates. I think there is a logic error somewhere towards the end with the it.next() code or possibly when one is deleted with the it.remove()????/

Any direction would be great. Here is what I have created.

import java.util.*;      //**all the Collections Framework classes are here
import javax.swing.*;

public class ArrayListTest {
    public static void main(String[] args) {
	String input, userstring;
	int size;
	int range;
	int randInt;
	int userAnswer;

        //**indexed list of (any kind of) objects (but not primitives).
        //**size expands as needed
	ArrayList myArrayList = new ArrayList();

	input = JOptionPane.showInputDialog( "Enter number of random ints to generate" );
	size = Integer.parseInt( input );

	input = JOptionPane.showInputDialog( "Enter upper range of the random ints" );
	range = Integer.parseInt( input );

	for (int i=1; i<=size; i++) {   //i is not an index, just a loop counter
	    randInt = (int)(Math.random()*range);  //random int between 0 and range-1
	    //uncomment if this code confuses you:
	    //System.out.println("generated int: " + randInt);
	    myArrayList.add(new Integer(randInt));  //**must wrap int into Integer
	}

	//**iterate over all the objects in the arraylist collection.
	Iterator it=myArrayList.iterator();
	//**an iterator is for accessing all the objects of collection, one by one.
	//**hasNext() is true until reach end of the collection.
	//**next()  returns the next object in the iteration.
	//**notice no for loop looping over indexes!
	System.out.println("Here are your random integers: ");
	while (it.hasNext())
	    //display them on one line, separated by a blank
	    System.out.print(it.next() + " ");
	System.out.println();


	//Used to Identify and Display duplicate integers
	//Used to prompt user if they want to delete the duplicate integers

        it=myArrayList.iterator();
	Set uniqueEntries = new HashSet();
        for (int i=1; i<=size; i++) {
            Object element = it.next();
            if (!uniqueEntries.add(element)) { // if current element is a duplicate,
            userAnswer = JOptionPane.showConfirmDialog(null,
						   it.next() +" Is a duplicate Integer in your list. Do you want to delete it?",
						   "Delete 'em?",
						   JOptionPane.YES_NO_OPTION);
	        if (userAnswer == JOptionPane.YES_OPTION) {
	            it.remove();		// remove it
	            it=myArrayList.iterator();
    	        }
	    }
        }
        //** sort
        Collections.sort(myArrayList);
        it=myArrayList.iterator();
	System.out.println();
	System.out.println("Here are your new sorted integers: ");
	while (it.hasNext())
	    System.out.print(it.next() + " ");
	System.out.println();

	//** smallest and largest values
        System.out.println("Min value in arraylist: " + Collections.min(myArrayList));
        System.out.println("Max value in arraylist: " + Collections.max(myArrayList));
    }
}



Thanks
Was This Post Helpful? 0
  • +
  • -

#7 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2791
  • View blog
  • Posts: 11,822
  • Joined: 20-September 08

Re: Identify and display duplicate elements in an array using an iterator

Posted 04 February 2012 - 05:02 AM

Look at the second line of commented-out code. This is the key problem - you're actually skipping an element by calling next() on the iterator. There's no need to reassign the Iterator (3rd comment-out) and an Iterator is best addressed in a while loop (1st comment-out)
        //for (int i = 1; i <= size; i++) {
        while(it.hasNext()) {
            Object element = it.next();

            if (!uniqueEntries.add(element)) { // if current element is a duplicate,
                userAnswer = JOptionPane.showConfirmDialog(null,
                        //it.next() +
                        element +
                        " Is a duplicate Integer in your list. Do you want to delete it?",
                        "Delete 'em?", JOptionPane.YES_NO_OPTION);

                if (userAnswer == JOptionPane.YES_OPTION) {
                    it.remove(); // remove it
                    //it = myArrayList.iterator();
                }
            }
        }


Was This Post Helpful? 1
  • +
  • -

#8 b.szabolcs  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 5
  • Joined: 04-February 12

Re: Identify and display duplicate elements in an array using an iterator

Posted 04 February 2012 - 05:22 AM

I've just run through your code.
I suggest using generic:
ArrayList<Integer> randoms = new ArrayList<Integer>();



So if you know what type of data you are working with, you dont have to cast, cause it automatically wraps it for you.
(if the types match)
randoms.add(randInt);



Plus I feel like it's easier to not use Iterators, instead you can do:
System.out.println("Here are your random integers: ");
	for( Integer random : myArrayList ){
		System.out.print( random + " ");
	}



As for the logical part, I don't really see what causes the problem. But I believe you can work with only a Set, 'cause if you generate the random integers, it will not gonna add duplicate ones from the begining. Choose wisely what collection you work with.

P.S. : Don't use Space for indenting.
Was This Post Helpful? 0
  • +
  • -

#9 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2791
  • View blog
  • Posts: 11,822
  • Joined: 20-September 08

Re: Identify and display duplicate elements in an array using an iterator

Posted 04 February 2012 - 05:53 AM

Quote

Plus I feel like it's easier to not use Iterators, instead you can do:


How would you remove using that?

Quote

P.S. : Don't use Space for indenting.


As opposed to ..?
Was This Post Helpful? 0
  • +
  • -

#10 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3719
  • View blog
  • Posts: 5,994
  • Joined: 08-June 10

Re: Identify and display duplicate elements in an array using an iterator

Posted 04 February 2012 - 06:06 AM

** Threads merged **

Do not double post your questions.
Was This Post Helpful? 0
  • +
  • -

#11 b.szabolcs  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 5
  • Joined: 04-February 12

Re: Identify and display duplicate elements in an array using an iterator

Posted 04 February 2012 - 06:48 AM

View Postg00se, on 04 February 2012 - 05:53 AM, said:

Quote

Plus I feel like it's easier to not use Iterators, instead you can do:


How would you remove using that?

Quote

P.S. : Don't use Space for indenting.


As opposed to ..?


public class ArrayListTest {

    public static void main(String[] args) {
        
        int size = 0;
        int range = 0;
        int randInt = 0;

        try {
            size = readInt("Enter number of random ints to generate");
            range = readInt("Enter upper range of the random ints");
        } catch (NumberFormatException nfe) {
            JOptionPane.showMessageDialog(null, "NumberFormatException error", "Error", JOptionPane.ERROR_MESSAGE);
        }


        ArrayList<Integer> randoms = new ArrayList<Integer>();

        for (int i = 1; i <= size; i++) {
            randInt = (int) (Math.random() * range);
            randoms.add(randInt);
        }

        System.out.println("Here are your random integers: ");
        System.out.println(randoms);


        ArrayList<Integer> unique = new ArrayList<Integer>();

        for (Integer random : randoms) {
            if (unique.indexOf(random) == -1) {
                unique.add(random);
            }

        }

        //** sort
        Collections.sort(unique);

        System.out.println("Here are your new sorted integers: ");
        System.out.println(unique);

        System.out.println("Min value in arraylist: " + Collections.min(unique));
        System.out.println("Max value in arraylist: " + Collections.max(unique));
    }

    //to reduce code redundancy
    public static int readInt(String msg) throws NumberFormatException {
        String input = JOptionPane.showInputDialog(msg);

        return Integer.parseInt(input);
    }
}


Was This Post Helpful? 0
  • +
  • -

#12 smithjr5  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 23
  • Joined: 04-February 12

Re: Identify and display duplicate elements in an array using an iterator

Posted 04 February 2012 - 07:09 AM

THANK YOU g00se.

You are the best.

I really, really appreciate your help!
Was This Post Helpful? 0
  • +
  • -

#13 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10694
  • View blog
  • Posts: 39,785
  • Joined: 27-December 08

Re: Identify and display duplicate elements in an array using an iterator

Posted 04 February 2012 - 12:38 PM

Quote

Plus I feel like it's easier to not use Iterators, instead you can do:
System.out.println("Here are your random integers: ");
	for( Integer random : myArrayList ){
		System.out.print( random + " ");
	}


This is just syntax sugar. The foreach loop relies on the object being Iterable, meaning an Iterator is used implicitly.

Quote

I suggest using generic:

I want to second this, and expand on this point. Use of non-generic Collections in Java is deprecated, as of Java 1.5. Generics also help enforce type-safety.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1