1

Hello to all the smart guys here,

i did my research on this topic and i KNOW it is written somewhere but i cannot find it anywhere (but i know i read about it a few weeks ago)... so here is my question:

With Java 8 it should be possible to use an interface as a collection-type in arrays or lists (not really sure about which one)... is anyone of you able to tell me what´s the name of this functionality is or just give me an abstract or clear example of code?

As far as i can remember the example was like: You have different types of objects that all share the same interface. With this interface it is possible to create a list or array that can store the different object-types.

I would be really happy if someone could help me with that... i really liked what i read there but now i have some sparetime and cannot find where i got this information from.

Thank you in advance!

//edit: Thank you for the fast answer, realSkeptic!!

4 Answers 4

2

This really has nothing to do with Java 8. If you have different objects which all implement the same interface, let's call it MyInterface, then you can create an array like this:

MyInterface[] myArray = new MyInterface[size];

And you can assign those objects to elements of this array. Of course, you can only use methods that are either in the definition of MyInterface or in the definition of Object - unless you cast your members back into their original class.

The same is true for lists. You can define a list:

List<MyInterface> list = new ArrayList<MyInterface>();

And then you can add any object that implements MyInterface to this list, with the same limitation on what you can do with the members when you get() them from that list: only methods of MyInterface and Object, unless you cast back.

Sign up to request clarification or add additional context in comments.

Comments

0

I think you're probably thinking of generics, which have been in Java since version 5. Let's say you have an interface called MyInterface and any number of classes that implement that interface, such as MyClassOne and MyClassTwo. It's possible to create a collection (such as a List) that will accept any class that implements MyInterface, like this:

List<MyInterface> theList = new ArrayList<MyInterface>();

You can then add to the list like so:

theList.add(new MyClassOne());
theList.add(new MyClassTwo());

The following will produce an compilation error:

theList.add("A String");

Objects returned from the list will be MyInterfaces. You won't immediately know if it's a MyClassOne or MyClassTwo:

MyInterface obj = theList.get(0);
if (obj instanceof MyClassOne) {
    System.out.println("It's MyClassOne");
} else if (obj instanceof MyClassTwo) {
    System.out.println("It's MyClassTwo");
}

It's a similar story for arrays - any MyInterface-implementing class can go in, and MyInterface instances come out:

MyInterface[] array = { new MyClassOne(), new MyClassTwo() };
MyInterface obj = array[0];
if (obj instanceof MyClassOne) {
    System.out.println("It's MyClassOne");
} else if (obj instanceof MyClassTwo) {
    System.out.println("It's MyClassTwo");
}

Comments

0

This is the complete example for arrays:

interface Foo {
    String bar();
}

class Impl1 implements Foo {
    String bar() {
        return "This is implementation 1";
    }
}

class Impl2 implements Foo {
    String bar() {
        return "This is implementation 2";
    }
}

public class Main {
    public static void main(String[] args) {
        Foo[] myArray = new Foo[2];
        myArray[0] = new Impl1();
        myArray[1] = new Impl2();
        for (int i = 0; i < myArray.length; i++) {
            System.out.println(myArray[i].bar());
        }
    }
}

Output:

This is implementation 1
This is implementation 2

Comments

0

What you're thinking about is called Java Generics.

public interface MyInterface { public void foo();}
public class Class1 implements MyInterface {public void foo() {System.out.println("1");}}
public class Class2 implements MyInterface {public void foo() {System.out.println("2");}}

public class Main {
   public static void main(String[] args) {
     List<MyInterface> list = new ArrayList<>();

     list.add(new Class1());
     list.add(new Class2());

     list.get(0).foo(); // Prints 1
     list.get(1).foo(); // Prints 2

     Class1 c1 = (Class1) list.get(0); // OK
     c1        = (Class1) list.get(1); // Runtime error - ClassCastException
  }

Also, you can use wildcards as follows:

public static void main(String[] args) {
    List<Class1> list1 = foo1(); // Compiler error - incompatible types
    List<Class1> list2 = (List<Class1>) foo2(); // Warning - unchecked cast

    Class1 class1 = list2.get(0); // OK

    List<Object> list3 = (List<Object>) foo1();

    Class2 class2 = (Class2) list3.get(0); // Runtime error - ClassCastException
}

private static List<? super MyInterface> foo1() {
    List<Object> list = new ArrayList<>();
    list.add(new Class1());
    return list;
}

private static List<? extends MyInterface> foo2() {
    List<? extends MyInterface> list1 = new ArrayList<Class1>();
    list1.add(new Class1()); // Compiler error: the compiler is not aware of the list's runtime type
                             // from the compiler's point of view, list1 could have runtime type List<Class2>

    List<Class1> list = new ArrayList<>();
    list.add(new Class1());
    return list;
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.