0

I've made a very simple generic class that store 2 variable of the same type, like this:

public MyClass<T>
{
    private T v1;
    private T v2;

    public MyClass(T v1, T v2)
    {
      this.v1 = v1;
      this.v2 = v2;
    {
 }

Now I need to implement, trough another non-generic class, a method that take an Object list of different types as input and give as output a list of MyClass<T> with couples of the same type.

My problem is that I cannot see a way to make something like this without knowing what types I'm working with, how do I instantiate the right type of MyClass every time? I've come this far without getting errors from eclipse

public List<MyClass<?>> match()
{
    List<MyClass<?>> list = new ArrayList<MyClass<?>>();

    for(Object obj : this.list)//not the same list it's a parameter of the
    {                     //non-generic class
        for(Object obj2 : this.list)
        {
            if(!(obj == obj2)&&obj.getClass().equals(obj2.getClass()))
            {
                MyClass<Object> couple = new MyClass<Object>(obj, obj2);
                insertCouple(couple, list);
            }
        }
    }

insertCouple is a private method that check if the couple are already in the output list, I've tried to implements Comparable on MyClass but made the coding even more complex.

As you can see I'm forced to stay generic but I can see there are problems with it. If there isn't a method to find and fill the specific type at run time, how do I have to wrote that to make it possible trough generics?

6
  • 1
    What are you trying to do? Explaining how to do what you want is like describing a program in terms of primitive machine instructions - it takes substantially more effort to first understand the purpose, for then to devise a working solution. I suspect you are trying some sort of search/match algorithm which pairs two sets of objects to each other, and your MyClass represents the matches, correct? May 23, 2013 at 11:36
  • 4
    What do you mean list is not the same list? list is exactly the same list. And what's wrong with new MyClass<Object>(obj, obj2)?
    – Old Pro
    May 23, 2013 at 11:38
  • There is no need of sorting, I just have to match couple of the same type and put them in the list, the method traverse the list and search for two objects of the same type and build a MyClass object with them. @OldPro it's a typo i forgot to add this.
    – Janbure
    May 23, 2013 at 11:52
  • 1
    The problem is that you want to match elements of two contra-variant lists (that is, lists with different kind of elements each) using an element-type-invariant predicate function (as expressed in your if statement), but then attempt to pair the "matched" elements to each other using an object of a generic class designed for a pair of elements of the same type. You either have to relax MyClass type parameter specification, or your list matching method will have to only accept lists of same element kind. Please correct me, if I am missing something. May 23, 2013 at 12:35
  • @amn The input list is only one(this.list in the for each), I must traverse it two times to be sure o not slip anything, also (a,b) is logically different than (b,a), the output list will indeed accept one type element only, MyClass<Object>. I wasn't able to check it early but the code actually works. I'm not sure if I understand that or if a nailed it by chance or, more important, is the right way o do it. Downcasting it's easy but not always he right path and doesn't work if I try to implements Comparable on MyClass.
    – Janbure
    May 23, 2013 at 17:23

2 Answers 2

1

You cannot decide which type of MyClass object to create at runtime (depending on the class of the matched objects), since all generic types are erased at compile time. You can read more on type erasure at:

http://docs.oracle.com/javase/tutorial/java/generics/erasure.html

3
  • I know about erasure,this exercise, although,didn't need the notion of it to be made. I know that it is not possible to extract a type at run time, that is exactly my problem, how do I have o set thing to be sure to instantiate the right object every time?
    – Janbure
    May 23, 2013 at 16:44
  • @Janbure: You always instantiate the right object. Erasure means that at runtime there is no difference between MyClass<String>, MyClass<Object> and MyClass<SomethingElse>. So just instantiate MyClass<Object> and, if necessary, check the actual type of the contained values at runtime.
    – creinig
    May 24, 2013 at 11:03
  • I think what leads to this issue is the original list storing all kind of types (String, Integer, whatever). So, if the input for a method is not bound to a type at runtime, you cannot bound the output to a type at runtime.
    – ag0rex
    May 29, 2013 at 9:10
1

From what I could gather in the comments, the solution is to build a list of pairs of elements from input list, based on a predicate.

class Match<T>
{
    T a, b;

    Match(T a, T b)
    {
        this.a = a;
        this.b = b;
    }
}

<T> List<Match<T>> match(List<T> list)
{
    List<Match<T>> matchList = new ArrayList<Match<T>>();

    for(T a : list)
    {
        for(T b : list)
        {
            if(a != b && a.getClass().equals(b.getClass()))
            {
                matchList.add(new Match<T>(a, b));
            }
        }
    }

    return matchList;
}

I believe I met your requirements:

Now I need to implement, trough another non-generic class, a method that take an Object list of different types as input and give as output a list of MyClass with couples of the same type.

The class containing the code above does not need be generic, and so the match method can be invoked with implicit specification of T, as in, you don't need to know T or specify it, in fact you can simply call match on a List<Object> or List (legacy code) if you will. The only restriction is that, the list you will get in return is typed as List<Match<K>> when you call match on a List<K>, but that's a good thing - generics are well applicable here.

You can even customize match, by having it operate on a predicate parameter:

class Predicate
{
    <T> boolean eval(T a, T b)
    {
        return a != b && a.getClass().equals(b.getClass());
    }
}

<T> List<Match<T>> match(List<T> list, Predicate predicate)
{
    List<Match<T>> matchList = new ArrayList<Match<T>>();

    for(T a : list)
    {
        for(T b : list)
        {
            if(predicate.eval(a, b))
            {
                matchList.add(new Match<T>(a, b));
            }
        }
    }

    return matchList;
}

As a final advice, avoid omitting type parameters for generic classes - that's a practice reserved for legacy code, and otherwise may indicate a logic problem with your code. It's the easiest thing to do - put Object or ? everywhere, but it is better to try to find true matching types for these generic specifications, in most cases.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.