This question already has answers here:
Create ArrayList from array
(42 answers)
Closed 6 years ago.
Hi I have two Java Files as below:
case 6:
System.out.println("List All Property Details For Rent >>>");
// System.out.println(Arrays.toString(Property_list));
int i=0;
while(i<count){
ppty.property_list[i].viewPropertyDetails("RENT");
i++;
}
System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
break;
}
}
}
}
Guys, This is basically an array of properties, and a Menu to do some operation with the list. I was planning to improve my code with a java ArrayList, because its more dynamic in nature. Could anyone tell me how I can convert this array (property_list) into an ArrayList? What are the changes do I need to make? Thanks in advance.
Your commented code is perfectly valid for initiliazing the arrayList.
ArrayList<Property> property_list = new ArrayList<Property>();
In java 7 or later you don't need to specify the second Property:
ArrayList<Property> property_list = new ArrayList<>();
Unlike the java Array you don't use bracket notation to access your variables you use .get(int index):
ppty.property_list.get(count)
To add a value you use .add(Object item);
ppty.property_list.add(new Property());
And you don't need to remember the size of ArrayList by storing it in a variable. The ArrayList has the .size() method which returns the number of elements in it.
Extra tips:
Here you can find extra methods the ArrayList has https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
You have setters and getters in your Property object. You could set the member variables to private and use them.
You should replace that ppty method with the constructor method like so:
public Property(int streetno,String streetname,
String suburb,
int postalcode,String contactperson,
String office,int phonenumber,
String openTime,String propertytype,
double price, String date){
this.StreetNumber = streetno;
this.StreetName=streetname;
this.Suburb=suburb;
this.PostalCode=postalcode;
this.ContactPerson=contactperson;
this.PhoneNumber=phonenumber;
this.Office=office;
this.OpenTime=openTime;
this.PropertyType=propertytype;
this.PropertyPrice=price;
this.Date = date;
}
This property_list should not be inside your Property object. This is something you should handle outside the object. For example in your public void displayMenuPanel() you could say ArrayList<Property> properties = new ArrayList<>(). If you put the list inside the object then it is tied with that object. If the object goes, the list goes.
Related
This question already has answers here:
Java List.contains(Object with field value equal to x)
(13 answers)
Finding out if a list of Objects contains something with a specified field value?
(6 answers)
Closed 1 year ago.
I have a list of a custom class object I created.
private List<Grocery> groceryList;
where Grocery class has name, price , quantity variables and getters...
And I want to check if a grocery product already exist in my list or not,if doesn't exist I want to add it to my list, here is my code:
CheckOut hisCheckOut = new CheckOut(itemName ,String.valueOf(price), String.valueOf(orderQuantity), String.valueOf(itemTotalPrice));
if(!(GroceryActivity.list.contains(itemName))){
GroceryActivity.list.add(hisCheckOut);
GroceryActivity.totalItemsPrice += itemTotalPrice;
}
itemName is a variable with a normal string name
.This is not working.
Your code is not working because you are checking itemName and the item itself.
Do it as follows:
boolean found=false;
for(Grocery g: GroceryActivity.list){
if(g.getItemName().equals(itemName)){
found=true;
break;
}
}
if(!found){
//...do whatever you want to do
}
Where itemName is the name of the item you want to checkout and getItemName is the getter of itemName in class Grocery.
The Grocery and the CheckOut are entirely different objects and you cannot actually compare two different types of objects using equals or contains. If you CheckOut class holds more items than the Grocery object, then I would recommend adding the Grocery object itself as an attribute to the CheckOut object so that you can use the comparison methods.
Hence the CheckOut class may look like as follows.
public class CheckOut {
public long checkOutTime;
// ... other extra attributes can go here
// Add the Grocery object as an attribute
public Grocery groceryItem;
}
Now when creating the CheckOut object, you are basically creating a grocery item in it, and now you can compare with the list of items that you have in your GroceryActivity.
boolean itemAdded = false;
for (CheckOut checkout : GroceryActivity.list) {
if (checkout.groceryItem.getName().equals(itemName) {
// Already added to the checkout
itemAdded = true;
break;
}
}
if (!itemAdded) {
GroceryActivity.list.add(hisCheckOut);
GroceryActivity.totalItemsPrice += itemTotalPrice;
}
I hope that helps!
This question already has answers here:
Create new object using reflection?
(2 answers)
What is reflection and why is it useful?
(23 answers)
Closed 7 years ago.
Suppose I have this class:
public class Person {
private String name;
private int age;
//setters and getters
...
}
The following code is not correct, but I want something similar.
String className="Person";
String att1 = "name";
String att2 = "age;
object o = createClassByName(className);
setValueForAttribute(o,att1,"jack");
setValueForAttribute(o,att2,21);"
Are you familiar with hashes?
I think you could use a HashMap, which is a common Hash implementation built into the Java library:
HashMap<String,Object> person1 = new HashMap<String,Object>();
person1.put("className", "Person");
person1.put("name", "Jack");
person1.put("age", 21);
Everytime you want to change the values, do: person1.put("name", "Jill")
And to get the values, it's person1.get("name")
If you want to take the class into account, you'll have to get the className and manually compare it in your code, to do different things according to the "class" of the object (which in reality is a HashMap, but nevermind).
Small reminder: doing things this way is considered very messy ;)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a model: fase.java with Integers and Strings + getters and setters:
public class Fase implements Serializable {
private Integer age;
private String name;
}
I want to store both the Integer and String in a Array or ArrayList. I now use this:
public String[] getAllValues(){
String[] values = {age.toString(), name};
return values;
Then in dataServiceImpl.java I retrieve the data with:
user.getFase().getAllValues()[0];
and retrieve the age.
This works, but I have a lot more than age and name, and was thinking if I could put everything in Fase.java in one Array/ArrayList, because they are Integer and String, and then retrieve it in dataServiceImpl.java?
Something like this in Fase.java: ArrayList <Objects> f3Values = new ArrayList <Objects>();
or Fase [] f3Array = new Fase[34];
and then retrieve that in dataServiceImpl.java with: ArrayList<Fase3.Fase3Array> f3List = new ArrayList<Fase3.Fase3Array>();
and use something like: user.f3List[0]; ?
First, you should learn how Java works.
Is Java "pass-by-reference" or "pass-by-value"?
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Then, you should learn how to properly create an encapsulated class, by defining both constructor(s) and getters, methods, setters (if needed; note that setters in general break encapsulation) etc.
Then, you should understand that to aggregate data you:
create a class, i.e. definition object that holds all the necessary fields,
create a storage aggregate (array, ArrayList, Map, whatever),
3a. create an object of a given class, setting the values of the fields,
3b. add the object to the aggregate,
3c. goto 3a until the aggregate is filled with the data needed.
Explaining that on the code provided, you should first have
public class Fase implements Serializable {
private int age;
private String name;
public Fase( int age, String name ) {
this.age = age;
this.name = name;
}
public int getAge() { return age; }
public String getName() { return name; }
}
then you can create the aggregate, e.g.
int FASE_MAX = 34;
Fase[] fArray = new Fase[FASE_MAX];
ArrayList<Fase> fArrayList = new ArrayList<Fase>(FASE_MAX);
then you create the objects and add them to the aggregate, e.g.
for( int i = 0; i < FASE_MAX; i++ ) {
Fase newFase = new Fase( i, "John Doe" );
fArrayList.add( newFase );
fArray[i] = newFase;
}
then, and only then, you can access the aggregate:
Fase someFase = fArrayList.get( n );
Fase someOtherFase = fArray[n];
Your Fase class can have whatever members and however many members you like and you can access them all. If you want an array of Fase then create one and each element of the array will contain all the Fase members.
Fase[] myArray = new Fase[34];
You have an array of 34 "Fase's" just add whatever members you want to your Fase class.
i need to fill an Array with different data types
InvoiceItem[] invoiceItems;
int test = 3;
int i = 0;
This needs to be in the Array:
InvoiceItem invoiceItem = new InvoiceItem();
invoiceItem.setItemType("TestItem");
invoiceItem.setArticleNo("TestItemID");
invoiceItem.setDescription("TestDescription");
invoiceItem.setQty(1);
invoiceItem.setPrice(new BigDecimal(20.00));
invoiceItem.setVat(new BigDecimal(5.0));
There is the possibility that there is more than one InvoiceItem (test=3), so it needs to be in a loop.
It has to be an Array, i need to pass it to another class which only accepts an Arrays.
How can i achieve this?
Edit: I will try to make my question more clear:
I need to know how to put these
invoiceItem.setItemType("TestItem");
invoiceItem.setArticleNo("TestItemID");
invoiceItem.setDescription("TestDescription");
invoiceItem.setQty(1);
invoiceItem.setPrice(new BigDecimal(20.00));
invoiceItem.setVat(new BigDecimal(5.0));
in an Array:
int countofInvoiceItem = 3; // there are 3 InvoiceItem
InvoiceItem[] invoiceItems = new InvoiceItem[countofInvoiceItem];
Where there can be more than one InvoiceItem.
Method looks like this:
public final ResponseCreateInvoice CreateInvoice
(Invoice Invoice, InvoiceItem[] InvoiceItems, Address DeliveryAddress, Address InvoiceAddress, String UserID, String Password)
(This is given and i can not change)
and returns
ResponseCreateInvoice inv = wsClient.createInvoice(invoice, invoiceItems, deliveryAddress, invoiceAddress, userID, password);
i am sort of new to Java (or arrays), so this may be an easy question, but i don't really get it. Also does it matter that there are Strings and Int, BigDecimal etc mixed together in an Array?
You just need to declare your array as an array of type T where T is a superclass of all the classes of the objects you want to fill it with. In the worst case, it would be Object but it's bad design 9 times out of 10.
I would recommend you to make a class that holds everything you need as follows:
public class YourClass{
int id;
double value;
String description;
//and so on
//create getters and setters
}
And you can use this class to pass array of objects to another class.
Put your objects of the class in the Array
For example
YourClass[] objects = new YourClass[SIZE];//define number of objects you need
And you can pass each and every objects separately or as a whole to another class.
And in your receiving class, you can have a constructor as:
public YourRecievingClass(YourClass[] object){
//and recieve here as you need; ask further if you need help here too
}
I think this is the best way to adopt though your question is not 100% clear
Based on your edit, your original question is off base. You do not want to create an array of different types but instead only want to create an array of one type and one type only, that being an array of InvoiceItems. You are confusing object properties with array items, and they are not one and the same. This code here:
invoiceItem.setItemType("TestItem");
invoiceItem.setArticleNo("TestItemID");
invoiceItem.setDescription("TestDescription");
invoiceItem.setQty(1);
invoiceItem.setPrice(new BigDecimal(20.00));
invoiceItem.setVat(new BigDecimal(5.0));
is where you are changing the properties of a single InvoiceItem.
It seems that your InvoiceItem class has String fields for item type, for article number, for description, an int field for quantity, a BigDecimal field for price and a BigDecimal field for VAT. And so your array would look simply like:
InvoiceItem[] invoiceItems = new InvoiceItem[ITEM_COUNT]; // where ITEM_COUNT is 3
You could use a for loop to then create your items:
for (int i = 0; i < invoiceItems.length; i++) {
invoiceItems[i] = new InvoiceItem();
}
And you could perhaps use the same for loop to fill in the properties of each InvoiceItem in the array:
for (int i = 0; i < invoiceItems.length; i++) {
invoiceItems[i] = new InvoiceItem();
invoiceItems[i].setItemType(???);
invoiceItems[i].setArticleNo(???);
invoiceItems[i].setDescription(???);
invoiceItems[i].setQty(???);
invoiceItems[i].setPrice(???);
invoiceItems[i].setVat(???);
}
But the unanswered question is, ... where do you get the data for each property of each InvoiceItem in the array? Is this information contained in a file? Is it inputted by the user? That is something you still need to tell us.
With which types of data? In general, you could use:
Object[] myArray;
All classes are subclasses of Object.
I'm looking for a way to store different data types in one fixed length collection so I can set/get elements by index. What's the best way to go about this?
Thanks!
EDIT:
Should this work?
private List t=new ArrayList();
t.set(2,"test");
I get this: java.lang.IndexOutOfBoundsException: Index: 2, Size: 0
Should this work?
private List t=new ArrayList();
t.set(2,"test");
No it shouldn't. A List doesn't automagically grow if you call set with a position that is beyond the end of the list. (See the javadoc.)
If you want to do that kind of thing you have to fill the List with null elements first; e.g.
private List t=new ArrayList();
for (int i = 0; i < LIMIT; i++) {
t.add(null);
}
...
t.set(2,"test");
But I'd also like to reiterate the point that various other answers have made. You should write a class and do this in a type-safe fashion. Stuffing things into an Object[] or List<Object> ... and hoping that you get the indexes and types right ... gives you fragile code. It is bad practice.
You need a Javabean. Create a class which represents the whole picture of all those different properties together. E.g. an User with id, name, gender, dateOfBirth, active, etc.
public class User {
private Long id;
private String name;
private Gender gender;
private Date dateOfBirth;
private Boolean active;
// Add/generate c'tor(s)/getters/setters/equals and other boilerplate.
}
This way you end up with a clear and reuseable abstraction.
User user = new User();
user.setName("John Doe");
user.setGender(Gender.MALE);
// ...
See also:
What is a Javabean?
You can do such a thing with List. It has get/set methods by index. I don't see why fixed length is important here.
You can always encapsulate precisely the behavior you want in a class of your own devising. You can have a backing array to manage it for you, but you'll have to do all the work yourself.
Can't you make an array of Objects? Which means everything except the primitive types (int, char, boolean, etc.); if you want to store them you have to wrap them in their corresponding Object Wrapper classes (Integer, Character, Boolean, etc.) So like:
mult_type[0] = "A String";
mult_type[1] = new Integer(42);
mult_type[2] = new Long(7149994000);
and so on. Although mult_type[i] is an Object by definition, the entry
stored there can be any subclass of Object. When you want to retrieve them,
you can examine them to find out what class they actually belong to. There
are a couple of ways to do this, one is to use the "instanceof" operator
like so:
if (mult_type[i] instanceof Integer) {
Integer anInteger = (Integer)mult_type[i];
int anInt = anInteger.intValue();
}
Notice that you have to "cast" the object to its actual class as you
retrieve it.