Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Need some help with Generics

  1. #1
    Member
    Join Date
    Apr 2012
    Posts
    42
    Thanks
    8
    Thanked 4 Times in 4 Posts

    Default Need some help with Generics

    The purpose of the project is to write code for a generic MySet class, as described below. Based off of my teachers template, I have already written the code that is seen below, as well as written up some test sets for use when the program is done. The problem I am having is understanding how to implement the generics in the add and remove methods mostly, as well as union and intersect. I believe the easiest way to do union and intersect is to have the methods go through their parameters and then return a third arrayList with the results. Can anyone give me some pointers or tips on a good starting point to do the rest of the methods.


    import java.util.*;
    public class MySet<T> implements Set<T>
    {
    	private ArrayList<T> set;
     
    	public MySet()
    	{
    		set = new ArrayList<T>();
    	}
     
    	public void clear()
    	{
     
    	}
     
    	public boolean add(T e)
    	{
     
    	}
     
    	public boolean contains(Object o)
    	{
     
    	}
     
    	public boolean isEmpty()
    	{
     
    	}
     
    	public boolean remove(Object o)
    	{
     
    	}
     
    	public int size()
    	{
    		return set.size();
    	}
     
     
    	public Object[] toArray()
    	{
    		ArrayList<T> temp = (ArrayList<T>) set.clone();
    		T[] array = (T[]) new Object[set.size()];
    		int i;
    		for (i=0; i<set.size(); i++)
    				array[i] = (T) temp.get(i);
    		return array;		
    	}
     
    	public static <T> Set<T> union(Set<T> first, Set<T> second ) 
    	{
     
    	}
     
    	public static <T> Set<T> intersect(Set<T> first, Set<T> second ) 
    	{
    		Set<T> set1 = first;
                    Set<T> set2 = second;
     
                    for (int i = 0; i < set1.size(); i++){
                        for (int j = 0; j < set2.size(); j++){
                            if (set1.get(i) == set2.get(i))
     
                        } 
                    }        
    	}
     
    	public void printAll()
    	{
     
    	}
     
     
    }
    public interface Set<T>
    {
    	boolean add(T e);
    	void clear();
    	boolean contains(Object o);
    	boolean isEmpty();
    	boolean remove(Object o);
    	int size();
    	Object[] toArray();	
    }
    public class MySetTests
    {
    	public static void main(String[] args)
    	{
    		test1();
    		test2();
    		test3();
    		test4();
    		//.....
    	}
     
    	//test cosntructor
    	public static void test1()
    	{
    		MySet<Integer> testSet = new MySet<Integer>();
    		assert(testSet.size() == 0);
    	}	
     
    	//test add on String 
    	public static void test2()
    	{
    		MySet<String> testSet = new MySet<String>();
    		assert(testSet.add("A") == true);
    		assert(testSet.add("A") == false);
    	}
     
    	//test add and contains
    	public static void test3()
    	{
    		Set<String> testSet = new MySet<String>();
    		assert(testSet.add("A") == true);
    		assert(testSet.contains("A") == true));		
    	}
     
    	//test add on Rectangle class
    	public static void test4()
    	{
    		Set<Rectangle> testSet = new MySet<Rectangle>();
    		assert(testSet.add(new Rectangle(3, 5)) == true);
    		assert(testSet.add(new Rectangle(3, 5)) == false);
    	}
     
     
    }
    public class Rectangle
    {
    	private int width;
    	private int length;
     
    	public Rectangle(int w, int l)
    	{
    		width = w;
    		length = l;
    	}
     
    	public void setW(int w)
    	{
    		width = w;
    	}
     
    	public boolean equals(Object o)
    	{
    		if ((o == null) || (! (o instanceof Rectangle)))
    			return false;
    		Rectangle rec = (Rectangle) o;
    		return rec.width == width && rec.length == length;
     
    	}
     
    	public String toString()
    	{
    		return "\nwidth: " + width + ", len: "+length;
    	}
    }
    Last edited by bankston13; October 4th, 2012 at 05:13 PM.


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Need some help with Generics

    Quote Originally Posted by bankston13 View Post
    ...I believe the easiest way to do union and intersect is to have the methods go through their parameters and then return a third arrayList with the results.
    Give it a try




    Quote Originally Posted by bankston13 View Post
    Can anyone give me some pointers or tips on a good starting point to do the rest of the methods.
    One at a time. Get one method working and tested before moving on.

  3. #3
    Member
    Join Date
    Apr 2012
    Posts
    42
    Thanks
    8
    Thanked 4 Times in 4 Posts

    Default Re: Need some help with Generics

    I'm getting a syntax error with my Intersect method. Its specifically at the .get part, which is telling me that it can't get the object that is in the i position of the arrayList. I'm not sure on the proper way that the sysntax should be.
    Last edited by bankston13; October 4th, 2012 at 05:52 PM.

  4. #4
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Need some help with Generics

    Please post the error message, your screen is hard to read from here.
    Also post the relevant code with the error.

  5. #5
    Member
    Join Date
    Apr 2012
    Posts
    42
    Thanks
    8
    Thanked 4 Times in 4 Posts

    Default Re: Need some help with Generics

    I can't even run the code, because of the syntax issue. here si the relevent code:

    public static <T> Set<T> intersect(Set<T> first, Set<T> second )
            {
     
     
                for (int i = 0; i < first.size(); i++){
                    for (int j = 0; j < second.size(); j++){
                        if (first.get(i) == second.get(i))               //****This is the error area****//
     
                    } 
                }        
    	}


    I pretty much know what I want to do after it as far as adding the results to an arraylist. The problem is that while I can do it rather easily with a predefined type, I can't seem to figure out how to do it when it involves generics. I'm not sure if I have to make a new arraylist with the T type or do something else.

  6. #6
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Need some help with Generics

    Quote Originally Posted by bankston13 View Post
    ... or do something else.
    When I am faced with an error, the first thing I do is to gather as much information as I can from the error. See if I can understand what the error is saying. Error messages usually describe what is not quite correct. After you understand what is wrong, you can start working on making it right.
    Quote Originally Posted by jps View Post
    Please post the error message, your screen is hard to read from here.

  7. #7
    Member
    Join Date
    Apr 2012
    Posts
    42
    Thanks
    8
    Thanked 4 Times in 4 Posts

    Default Re: Need some help with Generics

    After some more though, I think I've completed most of the code, aside from the union and intersect methods. What I'm trying to do is make the two arraylists that are passed into the two methods call the toArray method, that way they are converted to Arrays and somewhat easier to compare. I'm going off of Pseudo code that my teacher provided us for these two methods, and they both use Arrays and not arraylists to compare, so thats why I'm trying to convert. I understand the pseudo code for the most part, but I'm getting an error when I try to convert the arraylists to arrays. The syntax error I'm getting says this:

    incompatable types
    required: T[]
    found: Object[]
    where T is a type variable


    I can't figure out where to go from here. i understand that its an incompatability type, but I'm not sure on how to fix it when making my arrays. here is the Pseudo code I have if anyone needs it. I also have my revised MySet class as well.

    Intercept:

    C empty set
    for i 0 to n-1
    for j 0 to m-1
    if A[i] = B[j]
    add B[j] to C
    break out the j loop
    end if
    end for j
    end for i



    Union:

    C A //copy A to C
    for i 0 to m-1
    add true
    for j 0 to n-1 //determine if C already has B[i]
    if C[j] = B[i]
    add false
    break out of j loop
    end if
    end for j
    if add
    add B[i] to C
    end if
    end for i

    import java.util.*;
    public class MySet<T> implements Set<T>
    {
    	private ArrayList<T> set;
            private int size;
     
    	public MySet()
    	{
    		set = new ArrayList<T>();
    	}
     
    	public void clear()
    	{
    		int i;
                    for (i = 0; i < set.size(); i++){
                        set.remove(i);
                    }
    	}
     
    	public boolean add(T e)
    	{
    		boolean exist = contains(e);
     
                    if (exist == false){
                        set.add(e);
                        return true;
                    }
                    else
                        return false;
     
     
     
    	}
     
    	public boolean contains(Object o)
    	{
    		int i;
                    int result = 0;
                    for (i = 0; i < set.size(); i++){
                        if (set.get(i) == o)
                            result = i;
                        else
                            result = -1;
                    }
     
                    if (result == -1)
                        return false;
                    else
                        return true;
     
    	}
     
    	public boolean isEmpty()
            {
                    if (set.size() == 0)
                        return true;
                    else
                        return false;
    	}
     
    	public boolean remove(Object o)
    	{
     
    	}
     
    	public int size()
    	{
    		return set.size();
    	}
     
     
    	public Object[] toArray()
    	{
                    ArrayList<T> temp = (ArrayList<T>) set.clone();
    		T[] array = (T[]) new Object[set.size()];
    		int i;
    		for (i=0; i<set.size(); i++)
    				array[i] = (T) temp.get(i);
    		return array;		
    	}
     
    	public static <T> Set<T> union(Set<T> first, Set<T> second ) 
    	{
     
    	}
     
    	public static <T> Set<T> intersect(Set<T> first, Set<T> second )
            {
                T[] one = first.toArray();
                T[] two = second.toArray();                                                            ****//This method is one I need help with//****
    	}
     
    	public void printAll()
    	{
    		int i;
                    for (i = 0; i < set.size(); i++) {
                    System.out.println(set.get(i) + " ");
                }
    	}
     
     
    }

    I'm particularly looking for help with the Intersect and Union methods, but any pointers would be appreciated.

  8. #8
    Member
    Join Date
    Apr 2012
    Posts
    42
    Thanks
    8
    Thanked 4 Times in 4 Posts

    Default Re: Need some help with Generics

    Alright, so i figured out what was wrong with my toArray calls. I needed to make object arrays instead of T arrays. However, I'm having a hard time adding to the arraylist that I made to hold the common values in the Intersect method. The problem happens at my line that adds the value of the second array[j] to the arraylist. My error is basicaly saying that there is no method for add(object). I don't understand whats happening. here is the specific part of the code that I am having problems with.

    public static <T> Set<T> intersect(Set<T> first, Set<T> second )
            {
                Object[] one = first.toArray();
                Object[] two = second.toArray();
                ArrayList<T> third = new ArrayList<T>();;
                int i, j;
     
                for (i = 0; i < one.length - 1; i++ ){
                    for (j = 0; j < two.length - 1; j++){
                        if (one[i] == two[j]){
                            third.add(two[j]);                                             ****//This is line I am having trouble with//****
                        }
                    }
                }
    	}

Similar Threads

  1. Generics.
    By Kumarrrr in forum Java Theory & Questions
    Replies: 1
    Last Post: December 6th, 2011, 06:53 PM
  2. Do I HAVE to learn Generics?
    By hexwind in forum Collections and Generics
    Replies: 3
    Last Post: August 14th, 2011, 11:16 AM
  3. Generics
    By Kerr in forum Collections and Generics
    Replies: 2
    Last Post: May 19th, 2011, 06:44 PM
  4. Arrays and Generics
    By 999cm999 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 19th, 2011, 09:44 PM
  5. Generics
    By _lithium_ in forum What's Wrong With My Code?
    Replies: 21
    Last Post: December 6th, 2010, 07:08 PM