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) ...
Related
Guys I have created an ArrayList and I don't want to make it immutable. I just seek to find a solution as for how to not allow the ArrayList from removing the objects.
public final class EMailArchive {
private final String name;
private final ArrayList <EMail> emailList;
private final LocalDate date;
public EMailArchive(String name, ArrayList <EMail> emailList) {
this.name = name;
this.emailList = emailList;
date = LocalDate.now();
}
public String getName() {
return name;
}
public LocalDate getDate( ) {
return date;
}
public List <EMail> getEMailList() {
return emailList;
}
public void addEMailToArchive(final EMail mail) {
emailList.add(mail);
// the mail added to the list shall not be removed, but how do i do that
}
}
One way is to implement a subClass of ArrayList that override the remove method
class myArrayLit extends ArrayList {
public myArrayList() {
super();
}
#Override
public remove(int index) {}
}
This is a basic example, there are more method to override, to achieve your goal.
If the solution above with extending ArrayList is not appropriate for whatever reason, you could return a copy within the getter, like this:
public List <EMail> getEMailList() {
return new ArrayList<>(emailList);
}
Changes to the returned List will not be reflected back to the class member.
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 think I have got myself into a bit of muddle. I had teacher and student below in two separate addMember sections. For the purpose of what I am doing they have to in one section but when someone wants to add either student or teacher they need to be able to be added separately (so one call which will give the option of adding either). But my knowledge of arrayLists is not very good and as you can see isn't working very well. Any help be much needed and appreciated.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Committee {
private String name;
private List<Object> members;
public Committee(String name)
{
this.name = name;
members = new ArrayList<Object>();
List list = new ArrayList();
}
public void addMember(Student student, Teacher teacher)
{
List members1 = new ArrayList();
members1.add(student);
System.out.println(members1);
List members2 = new ArrayList();
members2.add(teacher);
System.out.println(members2);
}
public void printMembership()
{
System.out.println("Membership of the " + name + " Committee ");
Iterator<Object> it = members.iterator();
while (it.hasNext())
{
Object member = it.next();
System.out.println(members);
}
}
}
I'm not sure what you want to achieve, so I will write two solutions:
Situation where you want to have one list
interface Member {...}
class Student implements Member {...}
class Teacher implements Member {...}
public class Comittee {
private list<Member> members;
public void addMember(Member member) {
members.add(member);
}
public void printMembership() {
members.forEach(System.out::println);
}
}
Situation where you want to have two lists
interface Member ...
class Student implements Member ...
class Teacher implements Member ...
public class Comittee {
private list<Teacher> teachers;
private list<Student> students;
public void addMember(Student student, Teacher teacher) {
students.add(student);
teachers.add(teacher);
}
public void printMembership() {
getAllMembers().forEach(System.out::println);
}
private void getAllMembers(): List<Member> {
List<Member> allMembers = ArrayList<>(students.size() + teachers.size());
allMembers.addAll(teachers);
allMembers.addAll(students);
return allMembers;
}
}
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-
I have a List named resourceItems which containes ResourceItem objects.
public class ResourceItem {
private Long id;
private String name;
public ResourceItem(Long id, String name) {
this.id = id;
this.name = name;
}
// getters and setters...
}
public class SomeClass {
private List<ResourceItem> resourceItems = FindAllResourcesWebSerbice();
}
I would like to extend the objects in the List to include a boolean field named selected.
I've tried several variations of classes that extends ResourceItem (see below) including options using generics, but have not been successful. I would love a solution that uses generics for reuse.
public class ExtendedResourceItem extends ResourceItem {
private boolean selected = false;
public ExtendedResourceItem() {
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
public class SomeClass {
private List<ResourceItem> resourceItems = FindAllResourcesWebSerbice();
private List<ExtendedResourceItem> extendedResourceItem = resourceItems;
}
Any help is much appreciated.
Assuming ResourceItem implements equals and hashCode correctly, why not just keep a set of the ones that are selected:
Set<ResourceItem> selectedResourceItems = new HashSet<ResourceItem>();
Then you could add an item to the set when it's selected, remove it when it's deselected, and check to see if the set contains one when you need to know if it's selected.
This solution is very similar to Michael Myers' comment about using a Map<ResourceItem, Boolean>.
You should use composition, not inheritance here. From your description it sounds like ResourceItem is a domain object, but on screen, you should wrap it
class ScreenResourceItem {
ResourceItem item;
boolean selected;
}
Create a new list of ScreenResourceItem and put all the wrapped ResourceItems in it.
Generics and list covariance are not relevant here.
But using your snippet:
private List<ResourceItem> resourceItems = ... \\ some assignment;
private List<ExtendedResourceItem> extendedResourceItems = resourceItems;
is absolutely wrong. Since not any ResourceItem is guarantee to be also ExtendedResourceItem. (resourceItems list can contain objects that are ResourceItem but are NOT ExtendedResourceItem).
I don't see the point you want to reach, but if You want to transform resourceItems into list of resourceItems that have selected attribute, what about this concept:
public class ExtendedResourceItem {
private ResourceItem item = null;
private boolean selected = false;
public ExtendedResourceItem(ResourceItem item, boolean selected) {
this.item = item;
this.selected = selected;
}
// ... getters and setters
}
public class SomeClass {
private List<ResourceItem> resourceItems = FindAllResourcesWebSerbice();
private List<ExtendedResourceItem> extendedResourceItems = new ArrayList<ExtendedResourceItem>();
for (ResourceItem item: resourceItems) {
extendedResourceItems.add(new ExtendedResourceItem(item, false));
}
}
Is it the generics limits that are confusing? Try using the Upper Bounded Wildcards, e.g.
public class SomeClass {
private List<ExtendedResourceItem> extendedResourceItems = FindAllResourcesWebSerbice();
private List<? extends ResourceItem> resourceItems = extendedResourceItems;
}
Alternatively:
public class SomeClass {
private List<? extends ExtendedResourceItem> extendedResourceItems = FindAllResourcesWebSerbice();
private List<? extends ResourceItem> resourceItems = extendedResourceItems;
}
More information about wildcards Wildcards and Subtyping.