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);
}
Related
Image of variable hierarchy (Please Check)
I want this specific variable to be a list of usernames, and each of these users will have some bookings... I tried adding an arraylist within an arraylist but that doesnt allow the user to name the usernames, they have to be predefined, please give me a method to do this.
You can store any kind of object in an ArrayList.
You could define your own class Booking that contains information about a booking:
public class Booking {
// ... whatever information is necessary for a booking
}
And then define a class User that contains information about a user, including a list of bookings:
public class User {
private String name;
private List<Booking> bookings = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Booking> getBookings() {
return bookings;
}
// ... other methods as necessary
}
And then you can make an ArrayList of User objects, where each User object contains a list of Booking objects:
List<User> users = new ArrayList<>();
As the tittle says i want to save each new created object of Person's name in a list:
This is my code so far
package javaapplication4;
import java.util.*;
public class Person {
private String namePerson;
static List personList = new ArrayList();
{
personList.add(getPersonName());
}
public Person(String namePerson){
this.namePerson = namePerson;
}
public void setPersonName(String namePerson){
this.namePerson = namePerson;
}
public String getPersonName(){
return namePerson;
}
public void setPersonList(List personList){
this.personList= personList;
}
public static List getPersonList(){
return personList;
}
each time i am creating a person object its gets added as a 'null' spot in the list (when i use println).
how i change that to the name of the new object Person
like
Person Guy = new Person("NameOfGuy"); then list must be [NameOfGuy].
{
personList.add(getPersonName());
}
The above is called an instance initializer. It is executed before the constructor is executed. At that time, getPersonName will return null as you haven't yet set the value of namePerson.
Move that inside the constructor
public Person(String namePerson){
this.namePerson = namePerson;
this.personList.add(namePerson);
}
Sidenote: It is a bad practice to use raw types. You are using a raw List. It must be as
List<String> personList = new ArrayList<>();
What is a raw type and why shouldn't we use it?
As pointed out by #user7, you are adding the name into the list at the wrong place. What you should be doing is, adding person's name into list while you are creating person's object, i.e. inside your constructor. Replace your constructor with this :
public Person(String namePerson){
this.namePerson = namePerson;
personList.add(namePerson);
}
You can do the job Doing below changes to the Person class:
import java.util.*;
public class Person {
private String namePerson;
static List<String> personList = new ArrayList<>();
public Person(String namePerson) {
this.namePerson = namePerson;
personList.add(this.namePerson);
}
public void setPersonName(String namePerson) {
this.namePerson = namePerson;
}
public String getPersonName() {
return namePerson;
}
public void setPersonList(List personList) {
this.personList = personList;
}
public static List getPersonList() {
return personList;
}
}
Immutable Class with List
package com.text.immutable;
import java.util.Collections;
import java.util.List;
// An immutable class Student
public final class Student
{
final String name;
final int regNo;
final List<String> courses; // want to make Immutable
public Student(String name, int regNo, List<String> courses)
{
this.name = name;
this.regNo = regNo;
this.courses = Collections.unmodifiableList(courses);
}
public String getName()
{
return name;
}
public int getRegNo()
{
return regNo;
}
public List<String> getCourses() {
return courses;
}
}
Testing Immutable Class to Break Immutability
package com.text.immutable;
import java.util.ArrayList;
import java.util.List;
class ImmutablityTest
{
public static void main(String args[])
{
List<String> courses = new ArrayList<String>();
courses.add("java");
courses.add("spring");
courses.add("hibernate");
courses.add("rest");
Student s = new Student("ABC", 101, courses);
System.out.println("Before Update List");
System.out.println(s.getName());
System.out.println(s.getRegNo());
System.out.println(s.getCourses());
courses.add("Hibernate"); // Able to Change which affect final OutCome
//s.getCourses().add("SpringBoot"); // giving Exception in thread "main" java.lang.UnsupportedOperationException
System.out.println("After Update List");
System.out.println(s.getName());
System.out.println(s.getRegNo());
System.out.println(s.getCourses());
}
}
Output is
Before Update List
ABC
101
[java, spring, hibernate, rest]
After Update List
ABC
101
[java, spring, hibernate, rest, Hibernate]
why and how this new Course element added into the List as its from Client Side can be added up any time so how we can fix this issue as this immutable class should not allow to modifying after once created
this.courses = Collections.unmodifiableList(courses);
That creates, as the name says, an unmodifiable list. But that is just a view on the original list. Thus changes to that original list become visible in your "unmodifiable" view.
When in doubt: clone your list, like:
this.courses = new ArrayList<>(courses);
And then ensure that your getter does:
return Collections.unmodifiableList(courses);
Not the best in context of memory, but works:
// An immutable class Student
public final class Student
{
final String name;
final int regNo;
final List<String> courses; // want to make Immutable
public Student(String name, int regNo, List<String> courses)
{
this.name = name;
this.regNo = regNo;
this.courses = new ArrayList(courses);
}
public String getName()
{
return name;
}
public int getRegNo()
{
return regNo;
}
public List<String> getCourses() {
return new ArrayList(courses);
}
}
On input (in constructor) you create copy of list and on output (in getter) you create copy.
read about immutableLists and you'll find that an Immutable and Unmodifiable Are Not the Same.
I guess (from your question) you are expecting an unmodifiable list which you simply don't create...
see this answer for a proper solution
With Collections.unmodifiableList, it creates a wrapper around the original list and that wrapper object is unmodifiable. The original list can still be updated.
So, in order for the List<String> courses list to be immutable, you can use Apache collection common library.
List<String> immutableList =
com.google.common.collect.ImmutableList.of("Geeks", "For","Geeks");
ImmutableList has overridden the List.add method to always throw exception java.lang.UnsupportedOperationException
Second alternative is to create the list inside the constructor itself.
public Student(String name, int regNo, String... args)
{
this.name = name;
this.regNo = regNo;
courses = (List)Arrays.asList(args);
}
And call it like this :
Student s = new Student("ABC", 101, "a","a","a","a");
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);
I have following code:
public class Address {
private String city;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
And I have another class User with ArrayList<Address> as member variable as follows.
import java.util.ArrayList;
public class User {
private String name;
private ArrayList<Address> listOfAddresses ;
public ArrayList<Address> getListOfAddresses() {
return listOfAddresses;
}
public void setListOfAddresses(ArrayList<Address> listOfAddresses) {
this.listOfAddresses = listOfAddresses;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And in the class with the main method, I have created user object which has two member variable such as name and listofAddresses. Now, I need some guidance about how to set value for listOfAddresses using user object. And also how to retrieve using user object.
My main class looks like this.
import java.util.ArrayList;
public class ArrayImpl {
public static void main(String[] args) {
User user = new User();
user.setName("First User");
Address address = new Address();
address.setCity("Melbourne");
user.setListOfAddresses(address);
}
}
And I'm getting error at the user.setListofAddressess(address) as:
The method setListOfAddresses(ArrayList) in the type User is
not applicable for the arguments (Address)
My understanding is that listOfAddresses is an ArrayList of type Address and thus I'm trying to use setter method of listOfAddresses member variable to set it's value.
Can somebody please help me how to set listOfAddresses and retrieve using user object.
You have primarily two options:
Ugly Way
You retrieve the current list of addresses by calling the Getter, then adding your new address, then calling the Setter with your new list:
List<Address> addresses = user.getListOfAddresses();
addresses.add(address);
user.setListOfAddresses(addresses);
The smart and cool way
Your class User provides delegates to add and remove Addresses. For this, add methods for your purposes in your User class:
public void addAddress(Address a) {
this.listOfAddresses.add(a);
}
You are trying to set variable of type 'address' in user object but you are supposed to set an object of type ArrayList their.
User user = new User();
ArrayList<Address> ar=new ArrayList<>();
Address ad1=new Address();
ad1.setCity("Melbourne");
ar.add(ad1);
user.setListOfAddresses(ar);
Your method definition for setListOfAddresses in User class takes as argument an object of type ArrayList<Address>, but in your main you're trying to pass it an instance of Address.
This is the right approach:
ArrayList<Address> addrList = user.getListOfAddresses();
if (addrList == null) {
//If it's the first address you insert, you have to initialize the ArrayList
addrList = new ArrayList<Address>();
}
addrList.add(address);
Then to retrieve each address i straightforward:
ArrayList<Address> addrList = user.getListOfAddresses();
for (Address a : addrList) {
//do something with a....
}