I have been unable to add new elements in default array list .. somebody help me. i have searched about it for last 2 days but i couldn't understand the logic behind it
public class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
}
public class User2 {
public static List<User> list = new ArrayList<>();
public User2(int i, String abc){
list.add(new User(1,"abc"));
list.add(new User(2,"bcd"));
}
public List<User> getList() {
return list;
}
public void setList(List<User> list) {
this.list = list;
}
public static void main(String[] args) {
User2 user2 = new User2(3,"def");
List<User2> usr = new ArrayList<>();
usr.add(user2);
list.add((User) usr);
for(User temp: list){
System.out.println(" listing "+temp);
}
}
}
In this line:
list.add((User) usr);
You try to cast a List<User2> into a User. It won't work. I think that what the error must tell you.
But I might be able to see what you want to do. In Java you can't pass an User2 which doesn't have any link with User to a List<User>. You need to define a common interface and make both classes implement it. Or make the class User2 extend the class User.
list.add((User) usr); will provoke a ClassCastException as usr that is not very well named is a List. And a User cannot be cast to a List type.
What you need is adding the array list elements in another one :
list.addAll(usr);
A more readable code would be :
User2 user2 = new User2(3,"def");
List<User2> listToAdd = new ArrayList<>();
listToAdd.add(user2);
// add the local list elements to the static field list
list.addAll(listToAdd);
Related
I have this code to create a class User
public class User {
private String name;
private ArrayList<User> owners = new ArrayList<>();
public User(String name, ArrayList<User> owners) {
this.name = name;
this.owners = owners;
}
public String getName() {
return name;
}
public void addOwner(User owner) {
owners.add(owner);
}
If i create an instance of this class with
User jhil = new User(name, new ArrayList<>());
What do i do to add a string element to the arraylist
I've tried with the addOwner method with
jhil.addOwner(jhilsara);
but i get a the method addOwner(String) is undefined for the type User error
I've also tried with the ArrayList add method
jhil.add(jhilsara);
But that doesn't work either.
So my question is what do i need to do in order to add something to the arraylist of an instanced of my class User
You have your ArrayList set to contain objects of the User class, not Strings. Change the declaration of it to:
private ArrayList<String> owners = new ArrayList<>();
Then, you also have to change addOwner to:
public void addOwner(String owner) {
owners.add(owner);
}
I want to get the model numbers from the list only
['brand: Samsung, model number: VA2210-MH, size: 21.5', 'brand: Philipe, model number: 244E1SB, size: 21.5']
And I set create attributes and getter and setter of all attributes(only model number will be shown) in Monitor
public class Monitor{
public String brand;
public String modelNumber;
public double size;
public Monitor(String brand, String modelNumber, double size){
this.brand = brand;
this.modelNumber = modelNumber;
this.size = size;
}
public void setModelNumber(String amodelNumber){
modelNumber = amodelNumber;
}
public String getModelNumber(){
return modelNumber;
}
}
so I create a list and add the information into the list
and a method to create a set with model number by the method modelNumberSet()
import java.util.*;
public class ComputerShop{
private List<Monitor> monitorList = new ArrayList<>();
public void addMonitor(String brand, String modelNumber, double size){
Monitor newMonitor = new Monitor(brand, modelNumber, size);
monitorList.add(newMonitor);
}
public Set<Monitor> modelNumberSet(){
Set<Monitor> NewSet = new HashSet<>();
for (Monitor m : monitorList) {
NewSet.add(m.getModelNumber());
}
return NewSet;
}
}
I hope the model number will be added into a new set, the output looks like
[VA2210-MH, 244E1SB]
So I use for loop to incase I will add more information in the future, but the error comes out when I use add(). Why the array cannot be added into the new set? Am I using the wrong function?
Is there a better solution I should use?
Change Set<Monitor> to Set<String>. You are adding model numbers to the set and their types are String. You are trying to put a String where a Monitor is expected. Square peg in a round hole.
Fix the modelNumberSet() method as follows:
public Set<String> modelNumberSet(){
Set<String> newSet = new HashSet<>();
for (Monitor m : monitorList) {
newSet.add(m.getModelNumber());
}
return newSet;
}
I'm trying to make a program that matches a clients interests with aspects of a holiday, I have an array list of holidays and an array list of strings for the clients interests and I wanted to create a new array list which would add all elements that are contained in both. This is what I have but it comes up with a null pointer exception, Any ideas where I've gone wrong?
the debugger points towards the disjoint and at " int c1size = c1.size();"
Relevant parts of code...
In main...
ClientExt1 marina = new ClientExt1("Marina",14321,"marina.calder1#btinternet.com");
ArrayList<String> interests = new ArrayList<>();
interests.add("History");
interests.add("Music");
marina.setInterests(interests);
holidaySeller.getHolidayMatches(marina);
Client...
public class ClientExt1 {
private String name;
private int id;
private String email;
private HolidayExt1 holidayBooked;
private ArrayList<String> interests;
public ClientExt1(String name, int id, String email){
this.name=name;
this.id=id;
this.email=email;
}
public void setInterests(ArrayList interests) {
this.interests=interests;
}
public ArrayList<String> getInterests(){
return interests;
Company class...
public class CompanyExt1 {
protected ArrayList<StaffExt1> staffMembers;
protected ArrayList<HolidayExt1> holidays;
protected ArrayList<GuideExt1> holidayGuides;
protected ArrayList<AdventureExt1> adventureHolidays;
protected ArrayList<CultureExt1> cultureHolidays;
private ArrayList<String> matchedHolidays;
public ArrayList<String> findHolidayMatch(ClientExt1 client) {
ArrayList interests = client.getInterests();
int i;
for (i = 0; i < holidays.size() && i< interests.size(); i++) {
if (!Collections.disjoint(holidays.get(i).getAspects(), interests)) {
matchedHolidays.add(holidays.get(i).getName());
}
}
return matchedHolidays;
}
public void getHolidayMatches(ClientExt1 client){
System.out.println(client.getName() + ", the holidays recommended to you based on your interests from this company are:" + findHolidayMatch(client));
}
}
You need to initialize holidays before you use it and matchedHolidays before you add values to it in findHolidayMatch
I would actually make matchedHolidays a local variable instead of a class member since it is only used in the scope of the findHolidayMatch method.
I have created this class.
public class UserData {
private int user_Id;
private List<String> disease_List=new LinkedList<String>();
/*Constructor*/
public UserData(int u_id, List<String> d_list)
{
this.user_Id=u_id;
this.disease_List=d_list;
}
}
I created around 500 objects by reading data from file.
Now I want to search for values. For example If user enters a disease= allergy.
I want to iterate through all objects and display users that have allergy in disease_list.
I have searched on internet for this but have not found anything useful.
You have to add the userData objects in a collection and iterate them and access it's attributes say disease_list.
For example, if you've added the userData objects in a arrayList, you can iterate in the following way
for(UserData user:UserDataList){
if(user.disease_list.contains("allergy") {
//display the user details
}
}
I might have misunderstood the question.. But basically what you want to do is search for a certain keyword in the disease_List inside every UserData object, right?
So say you have added a String allergy = "allergy"; inside the disease_list.
What you want to do in order to find this you need to iterate through the disease_list instance.
for (int i = 0; i < disease_list.size(); i++) {
if(disease_list.get(i).equals("allergy")){
//Now you know this UserData object contains "allergy". Now you
//can choose to break the iteration and do something with
//the object.
}
}
You can use Lambdas expression (with java 8 or higher) to sort lists.
public class UserData {
private int user_Id;
private ArrayList<String> diseases;
/*Constructor*/
public UserData(int u_id, ArrayList<String> d_list)
{
this.user_Id=u_id;
this.diseases=d_list;
}
public ArrayList filter(String disease) {
return Arrays.stream(diseases).filter(x -> x.equal(disease)).toArray();
}
}
Java doesn't just automatically make a list of every object you create, you need to make the list yourself.
public class UserData {
/* This must exist somewhere */
private static List<UserData> everyone = new LinkedList<UserData>();
private int user_Id;
private List<String> disease_List=new LinkedList<String>();
/*Constructor*/
public UserData(int u_id, List<String> d_list)
{
this.user_Id=u_id;
this.disease_List=d_list;
everyone.append(this);
}
/* Iterator for all the objects */
public static Iterator<UserData> iterator() {
return everyone.iterator();
}
}
if you want to iterate here is one way
for(String disease:disease_list){
if(disease.equalsIgnoreCase("allergy")
log.info("You find out the Result");
}
else you can use contains() method
if(disease_list.contains("allergy")){
log.info("found the disease");
}
I want to make a program to create people and to show a list of such persons, but do not know if I am doing well and neither logic using "arraylist" to print the results anyone can help me? Thank you very much.
package person;
import java.util.*;
public class Person {
public int Id;
public String Name;
public boolean Show;
public ArrayList people;
public Person(
int identificator,
String thename,
boolean showornot
){
this.Id = identificator;
this.Name = thename;
this.Show = showornot;
}
public void InsertPerson(Person person, ArrayList list){
this.people = list;
list.add(person);
}
}
The main:
package person;
import java.util.*;
public class Trying {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
Scanner stdin2 = new Scanner(System.in);
Scanner stdin3 = new Scanner(System.in);
Scanner stdin4 = new Scanner(System.in);
ArrayList list_of_people;
list_of_people = new ArrayList();
int option = 0;
int identificador = 0;
String name = "";
boolean show = true;
name = “Toni”;
Person person1 = new Person(identificador, name, true);
person1.InsertPerson (person1, list_of_people);
Iterator ite = list_of_people.iterator();
while(ite.hasNext()){
System.out.println(list_of_people);
}
}
Thanks!
Problem: You are creating the arraylist "people" as a property of each "person" (Saying, each person has a list of people)
Quickfix:
Move public ArrayList people; to your Trying class.
Move public void InsertPerson(Person person, ArrayList list) to your Trying class as well.
Better fix:
I recommend using a PeopleManager class - which contains the arraylist "people" and the InsertPerson method. Then, you use the PeopleManager in Trying to build your people list.
public class PersonManager
{
ArrayList<Person> people;
public PersonManager()
{
people = new ArrayList<Person>();
}
public void InsertPerson(Person person)
{
people.add(person);
}
}
Then, you can remove the arraylist from Person, and the method InsertPerson from Person. You'll need to create a PersonManager in your Trying class.
public ArrayList people; does not belong in the Person class. I would suggest using it your client code (the Trying class) or creating a class People that inherits from ArrayList. You can then add a InsertPerson function to that class if you wish.
I would also suggest using a ArrayList for your collection rather than an ArrayList. See a generic collections tutorial here. You should also create getter/setter moethods instead of using public fields.
So, your classes would be:
public class Person { // ...
public class People extends ArrayList<Person> {
public void InsertPerson(Person person) {
this.add(person);
}
// ...
What everyone else is saying is true, but I think theoretically your code should still work. There is a problem with this line however...
while(ite.hasNext()){
System.out.println(list_of_people);
}
You are outputting the whole list every iteration and probably infinite looping. Change it to something like this...
while(ite.hasNext()){
Person curPerson = (Person)ite.next();
System.out.println(curPerson.Name);
}
A slightly more elegant solution is to ditch the iterator for a foreach loop...
for (Person person : list_of_people) {
System.out.println(person.Name);
}