Suppose we are creating a class in java where name and code are two private members and then are passing them in the list.
class A
{
private int code;
private string name;
public getCode()
{ return code;}
public setCode(int code){this.code=code;}
public getName()
{ return name;}
public setName(String name){this.name=name;}
class B {
List<A> l1=new List<A>
Now how to populate list A?
A obj = new A();
obj.setCode(123);
obj.setName("test");
List<A> list = new ArrayList<>();
list.add(obj);
Call l1.add(new A()). This will add a new instance of class A to your list, l1.
Documentation: http://docs.oracle.com/javase/8/docs/api/java/util/List.html#add-E-
Related
I have a class named "classroom" and i want send one arraylist with classroom.setMaterias(Arraylist). Is this code:
Class Clasroom
public class Aula implements java.io.Serializable {
private String nombre;
private String grupo;
private int tutor;
ArrayList<String> materias = new ArrayList<String>(); // ¿How create arraylist?
public Aula() {
// Constructor
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
I would like to know if I could, for example, send an "arraylist" through a SET and then make the "arraylist" that I created previously in my class "classroom" be exactly the same
I would not know how to create the arraylist, or the set or get methods. Can you help me please?
PD: This is the JSON ARRAY i talking about:
if (obj.has("materias")) {
JSONArray materias = obj.getJSONArray("materias");
datos.setArrayList(materias);
// System.out.println(materias); // ["DWES","DWEC","IW","DAW","IE"]
Class Clasroom
public class Aula implements java.io.Serializable {
private String nombre;
private String grupo;
private int tutor;
ArrayList<String> materias; // ¿How create arraylist?
public Aula() {
// Constructor
this.setArrayList(new ArrayList<>()); //Here you initialize the arraylist when you create an instance of this class.
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
//Here are the getters and setters.
public ArrayList<String> getList(){
return this.materias;
}
private void setArrayList(ArrayList<String> list){
this.materias = list;
}
The proper way of doing it is using getters and setters and using List interface rather than ArrayList<> directly.
List<String> materias = Collections.emptyList();
public Aula() {
// Constructor
}
public List<String> getMaterias() {
return materias;
}
public void setMaterias(List<String> materias ) {
this.materias = materias ;
}
public void addMaterias(String materia) {
materias.add(materia);
}
You can have additional addMaterias() method to add entries to your List.
public class Aula implements java.io.Serializable {
private List<String> materia = new ArrayList<>();
...
public void setMateria1(final List<String> aMateria) {
this.materia = aMateria;
}
public void setMateria2(final List<String> aMateria) {
this.materia.clean();
this.materia.addAll(aMateria);
}
}
setMateria1() replaces the list with the given argument, thus any changes (EG deletion of items,) made later to the one, is reflected in the other.
While setMateria2() copies the argument's items, thus deletion or insertion to any of them does not change the other one.
Also ArrayList is a concrete implementation of the interface List. It is preferable to declare variables as the base class or interface, instead of a concrete implementation.
public class Aula implements java.io.Serializable {
ArrayList<String> materias = new ArrayList<String>();
...
public ArrayList<String> getMaterias(){
return materias;
}
public void setMaterias(JSONList materias) throws JSONException {
materias.clear();
for(int i=0;i<materias.length();i++)
this.materias.add(materias.getString(i));
}
}
And put the exact same code into the classroom class.
Second way is to set the Lists in the constructor:
public class Aula implements java.io.Serializable {
ArrayList<String> materias = new ArrayLis<>();
...
public Aula(JSONList materias) throws JSONException {
for(int i=0;i<materias.length();i++)
this.materias.add(materias.getString(i));
}
public ArrayList<String> getMaterias(){
return materias;
}
}
Again same for classroom. And than you create them eg.
Aula aula = new Aula(materias);
Classroom classroom = new Classroom(materias);
This is assuming you have Strings in your list. Otherwise it depends on your data in the list.
If it contains other Lists it they need to be merged or skipped and so on...
If the json is not all Strings(e.g. has Sublists and Objects) and it should match the actual structure of your json I'd need that structure too and most probably an Arraylist of Strings might be the wrong Container for such a json - tree.
btw. better change classroom to Classroom(capital C for the classname) ...
I'm saving some ArrayList in Sharedpreferences. But I want to set my custom model to ArrayList in adapter cause get items with getter. I really tired too many solutions from stackoverflow but I couldn't do that.
private ArrayList<String> fullList = new ArrayList<>();
to
private ArrayList<MyCustom> fullList = new ArrayList<>();
My Custom Class:
public class InstagramUserSummary implements Serializable {
public boolean is_verified;
public String profile_pic_id;
public boolean is_favorite;
public boolean is_private;
public String username;
public long pk;
public String profile_pic_url;
public boolean has_anonymous_profile_picture;
public String full_name;
#Override
public int hashCode() {
return Objects.hash(username, pk);
}
#Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof InstagramUserSummary)) {
return false;
}
InstagramUserSummary user = (InstagramUserSummary) obj;
return pk == user.getPk();
}}
List coming like this:
[InstagramUserSummary(super=dev.niekirk.com.instagram4android.requests.payload.InstagramUserSummary#a4acf205, is_verified=false, profile_pic_id=1773528799482591987_1654599017, is_favorite=false, is_private=false, username=ququletta, pk=1654599017, profile_pic_url=https://instagram.fada1-5.fna.fbcdn.net/vp/8d99014623ed527e52512a20002d884b/5C387E45/t51.2885-19/s150x150/31203725_200759604054857_5778864946146181120_n.jpg, has_anonymous_profile_picture=false, full_name=Ququletta)]
Thanks.
First of all, there is no need to have the username field be a public member of the MyCustom class. Since you're exposing access to the field via getters/setters having it public is wrong.
Aside from that, you can easily use streams and a mapping function to create a new MyCustom instance from a Stream of String.
In order to avoid boilerplate code, I would go ahead and create a static creator method in MyCustom like this:
public class MyCustom {
private String userName;
public String getUserName() { return userName; }
public void setUserName(String userName) { this.userName = userName; }
public static MyCustom from(final String userName) {
MyCustom custom = new MyCustom();
custom.setUserName(userName);
return custom;
}
}
And then I would use this as a method reference to convert Strings over to MyCustoms thus collecting them into a new list like this:
List<String> list = new ArrayList<>();
List<MyCustom> customs = list.stream()
.map(MyCustom::from)
.collect(Collectors.toList());
Finally, also avoid initializing lists using the concrete type (e.g. ArrayList<String> someList = new ArrayList<>;'. It's much better to code the interfaces, thus doing something like List<String> someList = new ArrayList<>.
Solution:
Suppose you have a String variable in MyCustom class, like:
public class MyCustom {
private String strName;
public MyCustom(String name) {
this.strName = name;
}
public void setName(String name) {
this.strName = name;
}
public String getName() {
return this.strName;
}
}
then, you can do something like this:
for (MyCustom value : fullList) {
customFullList.add(new MyCustom(value))
}
Hope it helps.
I have two java classes as follows
public class A implements Serializable {
private String name;
private List<String> nameList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getNameList() {
return nameList;
}
public void setNameList(List<String> nameList) {
this.nameList = nameList;
}
}
public class B implements Serializable {
private String name;
private List<String> nameList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getNameList() {
return nameList;
}
public void setNameList(List<String> nameList) {
this.nameList = nameList;
}
}
Now I have an object of class A, Aobj, with both the fields initialized. I am using BeanUtils.copyProperties(Bobj, Aobj), but only the name field value is copied into the Bobj however Bobj.nameList is null. Is there a way to deep copy a object so that it copies all the fields including Collections like List, Map etc.
I somewhere heard about Dozer, not sure if that is meant for this purpose.
It is a bit strange that you have 2 different classes that are absolutely identical. But regardless, in order to deep copy one to another just write a 2 static methods in some Util class. One method will take class A and return class B and another will take B and return class A. Do your deep copying by yourself. Also, you can create class C that is the same as your classes A and B and then make your classes A and B just empty classes each extending C. It would give you the same structure, but would make your copying logic easier as you can just work with both A and B as instances of C.
I am trying to create an array of different objects and call class methods for individual objects.
class A
{
int ID,
String name,
public int getID()
{
return ID;
}
public void setID(int id
{
ID = id;
}
}
class B extends A
{
string name;
public string getName()
{
return name;
}
public void setName(string n)
{
name = n;
}
}
class Implement
{
public static void main(string[] args)
{
A[] a1 = new A[2];
a1[0] = new B();
a1[1] = new B();
a1[0].setID(123);
a1[0].setName("John"); //Error
}
}
I am not able to access the B class method. Can any one help me understand why it is not allowing me to access and how to achieve this... Appreciate your help..
Thanks
Unlike setID, A doesnt have a setName method so there's no polymorphism for that method.
This is because the reference type of a[0] is of parent class A where the method setName is not defined. To be able to call setname you can cast a[0] to type B
There are several syntax errors in your code. Also, you are creating the array with type A and setName is in type B. Here is updated code:
class A
{
int ID;
String name;
public int getID()
{
return ID;
}
public void setID(int id)
{
ID = id;
}
}
class B extends A
{
String name;
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
}
class Implement
{
public static void main(String[] args)
{
B[] a1 = new B[2];
a1[0] = new B();
a1[1] = new B();
a1[0].setID(123);
a1[0].setName("John");
}
}
Copy your code instead of retyping it. There are a lot of typos in here.
Use this:
class Implement
{
public static void main(String[] args)
{
A[] a1 = new A[2];
a1[0] = new B();
a1[1] = new B();
a1[0].setID(123);
((B)a1[0]).setName("John"); //No error
}
}
Because the compiler thinks every item of your list "is a" A because you declared a1 as a list of A. You can only call methods that belong to A. Suppose the 3rd item of your list was of type A, then you'd never be able to call setName() on it. Now, if you are certain that the 1st item of your list is a B, you can cast it:
((B)a1[0]).setName("name");
If you really want to use polymorphism, you need setName() to be defined on the parent class (A). Then, all the children can redefine what setName() does.
In addition to the included items, I have to store the name and the id of the List inside itself. Thus i extended an ArrayList as follows:
class MyList<E> extends ArrayList<E>{
private int id;
private String name;
MyList(int id, String name){
this.id = id;
this.name = name;
}
id getId(){ return id; }
String getName(){ return name; }
}
Now I realized, that this extension will only hold one specific type of objects. So how can I remove the generic character of my list?
class MyList<MyObject> extends ArrayList<E>
class MyList<MyObject> extends ArrayList<MyObject>
...and so on fails. I want to instantiate my list by
MyList mylist = new MyList();
...and it should automatically accept only MyObjects...
(Would it be better to create a wrapper which holds an ArrayList in addition to the meta? But because it is still a list, why remove all list-typical capabilities...)
You'll need
class MyList extends ArrayList<MyObject>
When you declare a type parameter for your class declaration like so
class MyList<MyObject> ...
the type MyObject> is not your type, it is a type variable that also has the name MyObject.
What you want, is to use your MyObject type as a type argument for the ArrayList type parameter as shown above.
But, as others have suggested, composition is probably a better way to do this, ie the wrapper you suggested in your question.
As has been answered already, the correct declaration would be
class MyList extends ArrayList<MyObject>
Even though you have no interest in overriding any ArrayList methods, you should consider composition over inheritance for this type of scenarios.
Example:
class MyList implements Iterable<MyObject> {
private final int id;
private final String name;
private final List<MyObject> list;
MyList(int id, String name){
this.id = id;
this.name = name;
this.list = new ArrayList<>();
}
int getId() { return id; }
String getName() { return name; }
MyObject get(int i) { return list.get(i); }
void add(MyObject o) { list.add(o); }
void remove(MyObject o) { list.remove(o); }
void remove(int i) { list.remove(i); }
void set(int i, MyObject o) { list.set(i, o); }
boolean contains(MyObject o) { return list.contains(o); }
int size() { return list.size(); }
#Override
Iterator<MyObject> iterator() { return list.iterator(); }
}
With this:
You can easily switch the ArrayList for a LinkedList, or any other list;
You control the methods this class offers;
If you like the chaining style, you may change those void for MyList;
etc.