how to get custom class from collection

C

column

//have simple class:

public class stud {
public String getData() {...}
...............
}


//And I have class that contains many of stud in collection data


public class studc {
ArrayList data = new ArrayList();
...............

//it is easy to add class in collection
public void add(stud s)
{
data.add(s);
}


public String enumerate()
{
String s = new String();

for (int i=0; i<data.size(); i++)
{

studentas f = data.get(i);
// !!!! it is not possible to get stud type element from colection
because arraylist returns
//only Object (not stud class)

s=s + f.getData()+"\n";
}

return s;
}
}


How to get stud type object from data?
 
M

Mark

//have simple class:

public class stud {
public String getData() {...}
..............

}

//And I have class that contains many of stud in collection data

public class studc {
ArrayList data = new ArrayList();
..............

//it is easy to add class in collection
public void add(stud s)
{
data.add(s);
}

public String enumerate()
{
String s = new String();

for (int i=0; i<data.size(); i++)
{

studentas f = data.get(i);
// !!!! it is not possible to get stud type element from colection
because arraylist returns
//only Object (not stud class)

s=s + f.getData()+"\n";
}

return s;
}

}

How to get stud type object from data?

Basic answer: Use a cast. "studentas f = (stud) data.get(i);"
Advanced answer: Use stud as a type parameter: ArrayList<stud>
Side issue: Always use a capital letter at the start of class names to
distinguish them from variable names: Java doesn't care, but other
Java programmers do.

Mark
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top