Split Into Lists based on Object, without instanceof

groovy list of objects
java instanceof generic list
java list
java instanceof generic type
groovy list find
groovy sort list
groovy list size
groovy collect

Im going to go straight to the point.

I got 3 classes. Person, Professor and Student. (Persona, Profesor, Alumno). Both professor and student extends from Person. But Person can also be instantiated, because it's not abstract.

I have 50 persons, randomly generated on a list. It can be any kind, person professor or student. I want to separate them each into a different list.

At the moment, I did this:

for(Persona persona : personas) {
        if(persona instanceof Profesor) {
            profesores.add((Profesor) persona);
        }
        else if(persona instanceof Alumno) {
            alumnos.add((Alumno) persona);
        }
        else {
            nuevasPersonas.add(persona);
        }
    }

profesores is a list of Professor

alumnos is a list of Students

nuevasPersonas is a list of Persons

Which works perfect. But I was told not to use instanceof, so I don't get used to it.

Any ideas on how to separate them into lists, without the use of instanceof?

Thanks.

I would use instanceof, why wouldn't you want to get used to it?

Anyway, an alternative could be having a variable type (with getter, but no setter), in Person (=0), and override it to 1 and 2 in Professor and Student. Then,you would test the variable instead of using instanceof.

Proceedings of the Fourth ACM SIGPLAN International Conference on , Public fields could be placed directly in an object's fields record, without needing a method named allviews that takes the self object and returns a list of Tagged values. To test if an objecto is an instanceof class c (or interface i), we invoke the our technique does not use hierachical extensible sums or variance-based​  Simple split of string into list. If you want to split any string into a list (of substrings) you can use simply the method split(). It can be used: without parameter - then space is used as separator. with parameter - comma, dot etc - see next section.

Perhaps your teacher wants you to create an overriden method which answers the question isStudent or isProfessor?

However, since this gives us no extra information that is not already available via the instanceof operator, this is a contrived example where adding these redundant methods is not really a great design decision. Unfortunately in beginner classes you will sometimes encounter such contrived examples which are overly simplified for the purpose of teaching a particular language concept.

Eclipse Plug-in Development: Beginner's Guide, toString(); } else if (element instanceof ZoneId) { return ((ZoneId) element).getId().​split("/")[1]; } else { return "Unknown type: " + element. an empty string—so that when an unexpected value type is seen in the list, it can be recognized and public boolean hasChildren(Object element) { if (element instanceof Map) { return !(( Definition and Usage. The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When max is specified, the list will contain the specified number of elements plus one.

You can overload an "add" method with each of the object types - something like the following code.

The main method just adds instances of three different Objects to the ObjectSplitter class - it separates them out in to different Collections

public class ObjectSplitter {

public static void main(String ... args){

    ObjectSplitter d = new ObjectSplitter();
    d.addToCollection(new Object1());
    d.addToCollection(new Object1());
    d.addToCollection(new Object2());
    d.addToCollection(new Object1());
    d.addToCollection(new Object1());
    d.addToCollection(new Object1());
    d.addToCollection(new Object2());
    d.addToCollection(new Object3());
    d.addToCollection(new Object1());

    System.out.println("Num Ob1s : " + d.getOb1sSize());
    System.out.println("Num Ob2s : " + d.getOb2sSize());
    System.out.println("Num Ob3s : " + d.getOb3sSize());

}

private List<Object1> ob1s = new ArrayList<>();
private List<Object2> ob2s = new ArrayList<>();
private List<Object3> ob3s = new ArrayList<>();

void addToCollection(Object1 o){
    ob1s.add(o);
}

void addToCollection(Object2 o){
    ob2s.add(o);
}

void addToCollection(Object3 o){
    ob3s.add(o);
}

int getOb1sSize(){
    return ob1s.size();
}

int getOb2sSize(){
    return ob2s.size();
}

int getOb3sSize(){
    return ob3s.size();
}

static class Object1 {

}


static class Object2 extends Object1 {

}

static class Object3 extends Object2 {

}

}

Avoiding instanceof vs abstract God Class. Do I have an alternative , Downcasting is not "evil" in your case, but that master base class You have collections of objects and it would be handy to just order to process only a subset of the possible node types, so you filter a list of This should be quite simple to do at object creation time, and usually enables splitting up of a lot  The split() method returns a string [] instance and the tokenize() method returns a list instance tokenize() ,which returns a list, will ignore empty string (when a delimiter appears twice in succession) where as split() keeps such string.

also you can use getClass().getSimpleName() as below:

public static void main (String[] args) throws java.lang.Exception
{
    List<Test1> list = new ArrayList<>(2);
    Test1 o1 = new Test1();
    list.add(o1);
    Test2 o2 = new Test2();
    list.add(o2);
    for (Test1 test : list) {
        System.out.println(test.getClass().getSimpleName());
    }
}
static class Test1{

}
static class Test2 extends Test1{

}

in the for loop you can have a if condition as like as below code to do your job:

for (Test1 test : list) {
    String className = test.getClass().getSimpleName();
    if(className.equals("Test1")) {
       System.out.println("Test1");
    } else if(className.equals("Test2")) {
       System.out.println("Test2");
    }
    System.out.println();
}

another solution according to overriding methods is:

public static void main (String[] args) throws java.lang.Exception
{
    List<Test1> list = new ArrayList<>(2);
    Test1 o1 = new Test1();
    list.add(o1);
    Test2 o2 = new Test2();
    list.add(o2);
    for (Test1 test : list) {
        test.addToMyTypeList();
    }
    for(Test1 test : Test1.list) {
        System.out.println(test.getClass().getSimpleName());
    }
    for(Test1 test : Test1.list) {
        System.out.println(test.getClass().getSimpleName());
    }
}
static class Test1{
    public static List<Test1> list = new ArrayList<>();
    public void addToMyTypeList() {
        String className = test.getClass().getSimpleName();
        if(className.equals("Test1")) {
                    Test1.list.add(this);
        }
    }
}
static class Test2 extends Test1{
    public static List<Test1> list = new ArrayList<>();

    @Override
    public void addToMyTypeList() {
        String className = test.getClass().getSimpleName();
        if(className.equals("Test2")) {
                    Test2.list.add(this);
        }
    }
}

Learn Java for Android Development, First, this class's String(String s) constructor doesn't initialize a String object to a System.out.println("abc".length()); and System.out.println("abc" instanceof String);​. However, String objects created via String constructors are not interned, to split a string's comma-separated list of values into an array of String objects. I have an ArrayList of similar objects. Now I have to split the lists into multiple lists based on a property of these objects. Here is the sample data set List: A{1, A} A{2, A} A{3, B} A{4, B} A{5, B} A{6, C} Result should be List 1: A{1, A} A{2, A} List2: A{3, B} A{4, B} A{5, B} List3: A{6, C} Any body has a easier way doing this

Beginning Java 7, In reality, a string literal is a String object. You can prove this to yourself by executing System.out.println("abc".length()); and System.out.println("abc" instanceof String);. However, String objects created via String constructors are not interned, to split a string's comma-separated list of values into an array of String objects. Python string method split () returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num. Following is the syntax for split () method − str.split (str="", num=string.count (str)). str − This is any delimeter, by default it is space.

Working with collections, Most of those are based on the Java collection types and decorated with 'a', 2.5​, 2.5f, 2.5d, 'hello', 7g, null, 9 as byte] //objects can be of different types; index not allowed with get() assert false } catch (e) { assert e instanceof indexOf('z') == -1 // index -1 means value not in list assert ['a', 'b', 'c', 'd', 'c']. Upcasting narrows the list of methods and properties available to this object, and downcasting can extend it. A reference is like a remote control to an object. The remote control has more or fewer buttons depending on its type, and the object itself is stored in a heap.

Java Language, now Object } }. Since types are gone, it's not possible for the JVM to know which type is T . public boolean isAList(Object obj) { return obj instanceof List<​?>; }. Let's see a couple of examples to split a comma separated String in Java. You can also see Java Regular Expressions, taming the java.util.regex engine to learn the full power of Java regular expression. Split a comma-delimited String into an array This is the simplest example of splitting a CSV String in Java.

Comments
  • please don't post images of code. post the text itself using proper formatting
  • @PatrickParker Fixed!
  • Unless there is some sort of tag to indicate the type of the Persona; or isProfesor(), isAlumno() methods; or some means of doing double dispatch, you've got to do this with instanceof.
  • The reason I was thought to why not use instanceof, was because most of the times it can be fixed using polymorphism, which is a better and more cleaner solution.
  • Same comment as here.
  • @Turner in that case, the problem changes and I prefer to have an enum of the types I have guaranteed to route their objects to separate lists and in the for loop, I will iterate on the enum keys too. Therefore, when the question changes, there is no need to use the same method. :)