initializing an object in an array - java

I've been playing around with arrays for some time and this problem has been troubling me.
I created a user defined object and declared it in an array like this: `Property regesteredAssets[] = new Property[200];
And here's my constructor: `
public Property(String newPropertyName,String newPropertyAddress,String newPropertyType, String newPropertyDescription)
{
propertyName[arraySequence] = newPropertyName;
propertyFullAddress[arraySequence] = newPropertyAddress;
propertyType[arraySequence] = newPropertyType;
propertyDescription[arraySequence] = newPropertyDescription;
arraySequence++;
}
I want to initialize each array regesteredAsssets[] according to my desire. How can I do it?
Do I have to use arrays in my attributes in the Property class too?

You do not need your attributes to be arrays, unless a particular asset has multiple of something. In this case, I don't think it does. You can greatly simplify your code as follows:
public class Property {
private String name, address, type, description;
public Property(String name, String address, String type, String description) {
this.name = name;
this.address = address;
this.type = type;
this.description = description;
}
public static void main(String[] args) {
Property[] registeredAssets = new Property[200];
registeredAssets[0] = new Property("Joe Bloggs", "555 Fake St.", "IMPORTANT", "Lorem Ipsum Dolor");
// etc.
}
}

If you have an array of type Property, you can set each of the elements up using the following code:
regesteredAssets[0] = new Property( enterYourParametersHere );
I assume the fields in your Property constructor are single fields, and therefore you do not need to set them using the array notation field[index] = value, and indeed, if the Property class is of the consistency I think it is, then this will produce a compilation error.
If you wanted to set up multiple entries in your array, you could perform the initialisation step inside a loop, providing a loop index to the index of the array as below:
for( int i = 0; i < 10; i++ )
{
regesteredAssets[i] = new Property( enterYourParametersHere );
}
I hope this helps...

Related

Should I initialize object values?

The question may sound a bit silly, but should an object class look something like this:
class Book {
String title;
int year;
///so on and so forward
}
or should it look like this?
class Book {
String title = "";
int year = 0;
///so on and so forward
}
i understand that actual values should be set by the constructor (or setValue methods), but should the initial values be null, or 0/"" ?
Edit: Im trying to work with the object values as strings (replacing certain characters, etc), which doesnt work if the value is null; i wasnt sure if i should add an "if" clause or simply initialize values to an empty string
It should look something like this:
public class Book {
private String title;
private int year;
}
public Book(String titleIn, int yearIn) {
title = titleIn;
year = yearIn;
}
And the way you should create the object is:
Book harryPotter = new Book("Harry Potter", 2014);

Constructor calling constructor with arguments

I need to have a class with two constructors, one with and one without arguments. The one without is supposed to call the other with Randomized arguments, so not default ones.
Here is some sample code:
public Human(int ageIn, String nameIn){
this.name = nameIn;
this.age = ageIn;
}
public Human(){
String[] names = {"Peter", "Olof", "Alva", "Sanna", "Carl", "Illona"};
double random = Math.random();
int nameIndex = (int)(names.length*random+0.5);
String name = names[nameIndex];
random = Math.random();
int age = (int)(100*random+0.5);
this(age, name);
}
The thing that makes this hard is that this() has to be in the beginning of a constructor, but I have to define and figure out name and age before I can call the first constructor with them.
Is there any way around this?
You can make static methods which make these random values. Then on line 1 of your constructor you can call:
public Human(){
this(getRandomAge(), getRandomName());
}
Alternatively you could create a factory method to create a 'random' Human:
public class MyProgram {
public static void main(String[] args) {
Human someRandomStranger = Human.createRandomHuman();
//...
}
}
public class Human {
public Human(int ageIn, String nameIn){
this.name = nameIn;
this.age = ageIn;
}
// ...
public static Human createRandomHuman(){
String[] names = {"Peter", "Olof", "Alva", "Sanna", "Carl", "Illona"};
double random = Math.random();
int nameIndex = (int)(names.length*random+0.5);
String name = names[nameIndex];
random = Math.random();
int age = (int)(100*random+0.5);
return new Human(age, name);
}
}
This would keep your constructors clear from stuff that shouldn't be there in the first place.
A default constructor that randomly assigns values to it's fields might be accidentially called in your code and create unwanted results.
A properly named factory method on the other hand would help prevent such mistakes and clearly communicate your intention.
How about something like this?
public class Human {
public Human() {
this(null, -1);
}
public Human(String name, int age) {
if(name == null) {
name = //your random name generation code
}
if(age == -1) {
age = //your random age generation code
}
this.name = name;
this.age = age;
}
}
Don't mix concerns. A Human should not care about choosing a random name based on a predefined set of names nor compute a random age !
I would rather delete the no-arg constructor (except if you have one defined value for a name and for an age, but it seems that it's not your case) and extract this logic outside of Human, typically in a HumanFactory.

ArrayList - possible to read out the element name?

Heyho everyone!
My project is a bit bigger so I decided to short it a bit and showing only the problem code, which i have currently. On the first, im programming on a console. Reading six strings from a Scanner, before I save them in a variable i'm doing a validity check (length, special signs, etc...). So I decided to make this in an extra method check_newCustomer(). I used an ArrayList to return more as one value. So now is the point that I need the captured inputs in the main() function or any other method which writes the new Customer in the database. Problem is now i don't know how I can reference to userID, firstname, secondname... in other method. I just can refer with an index. But I would prefer it when i can use the variable names to refer to it. So its much easier on the other methods to handle with strings. Possible?
public static void main(String[] args) {
ArrayList<String> newCustomer = new ArrayList<String>();
check_newCustomer (newCustomer);
}
public static void check_newCustomer(ArrayList<String> newCustomer) throws IOException {
String userID = null;
String firstname = null;
String secondname = null;
String street = null;
String zipcode = null;
String city = null;
// validity check before I fill the input fields
...
// fill arraylist
newCustomer.add(userID);
newCustomer.add(firstname);
newCustomer.add(secondname);
newCustomer.add(street);
newCustomer.add(zipcode);
newCustomer.add(village);
}
Thanks!
No, the value in the ArrayList is just a reference. The fact that you originally referred to it using a different variable is irrelevant.
You could use a Map<String, String> instead... but it would be much cleaner to have a Customer class which had fields for the various pieces of information. If you want multiple customers, you can then have a List<Customer>.
One needs to make a class Customer, just a group of fields. Instead of a list of Strings.
public class Customer {
String userID;
String firstname;
String secondname;
String street;
String zipcode;
String city;
}
And in the code:
Customer newCustomer = new Customer();
newCustomer.userID = ....
System.out.println(newCustomer.userID);
When you pass check_newCustomer (newCustomer); you are only passing a copy of the array list. In this case, the original array list newcustomer is left intact while a new copy whose scope is within the method check_newCustomer is where all the strings are stored. You can either create a new class for Customers or you can create a class and have your array list as a class variable and check_newCustomer as a class method. In the latter case, it is much simple.
class customer
ArrayList<String> newCustomer;
public static void main(String[] args) {
newCustomer = new ArrayList<String>();
check_newCustomer ();
}
public static void check_newCustomer() throws IOException {
String userID = null;
String firstname = null;
String secondname = null;
String street = null;
String zipcode = null;
String city = null;
// validity check before I fill the input fields
...
// fill arraylist
newCustomer.add(userID);
newCustomer.add(firstname);
newCustomer.add(secondname);
newCustomer.add(street);
newCustomer.add(zipcode);
newCustomer.add(village);
}
}
This must work.

Creating an array of Sets in Java

I'm new to Java so I'm probably doing something wrong here,
I want to create an array of Sets and I get an error (from Eclipse).
I have a class:
public class Recipient
{
String name;
String phoneNumber;
public Recipient(String nameToSet, String phoneNumberToSet)
{
name = nameToSet;
phoneNumber = phoneNumberToSet;
}
void setName(String nameToSet)
{
name = nameToSet;
}
void setPhoneNumber(String phoneNumberToSet)
{
phoneNumber = phoneNumberToSet;
}
String getName()
{
return name;
}
String getPhoneNumber()
{
return phoneNumber;
}
}
and I'm trying to create an array:
Set<Recipient>[] groupMembers = new TreeSet<Recipient>[100];
The error I get is "Cannot create a generic array of TreeSet"
What is wrong ?
From http://www.ibm.com/developerworks/java/library/j-jtp01255/index.html:
you cannot instantiate an array of a generic type (new List<String>[3] is illegal), unless the type argument is an unbounded wildcard (new List<?>[3] is legal).
Rather than using an array, you can use an ArrayList:
List<Set<Recipient>> groupMembers = new ArrayList<Set<Recipient>>();
The code above creates an empty ArrayList of Set<Recipient> objects. You would still have to instantiate every Set<Recipient> object that you put into the ArrayList.
Arrays don't support Generics. Use an ArrayList:
ArrayList<Set<Recipient>> groupMembers = new ArrayList<Set<Recipient>>();
You might want to consider using Guava's Multimap where the key is the index. This will handle creating the Sets for each index as you need them.
SetMultimap
SetMultimap<Integer, Recipient> groupMembers;

Specific Datatype for this situation?

I want to pull data from a database. Name, Age, Sex, Location.(maybe more fields)
I want to hold the data in an object similar to how I would expect it to look in a JSON object.
Like:
myData{
row1[name:beavis, age:48, sex:male, location:Joburg]
row2[name:quintus, age:43, sex:, location:Helsinki]
...up to say 500 rows
}
So i'd like to be able to do tempName = row(i).name and so on in java.
Any suggestions.
// Defines a Person datatype
public class Person {
// fields
private String name;
private int age;
private String location;
// gets the value of a field
public String getName() {
return name;
}
// sets the value of a field
public void setName(aName) {
this.name = aName;
}
}
What I did here was define a Person type with a number of fields. Also I give here an example of a setter and getter for the name field. You can put them in an array or collection. For example:
Person people[] = new Person[2];
people[0] = new Person();
people[0].setName("Alice");
You can also dispense with the setters and getters by making the fields public, but I wouldn't recommend it.
A straight translation of that data structure would be along the lines of
List<Map<String, Object>> myData
so you'd be able to call
tempName = (String) myData.get(i).get("name");
Like the JSON array, this doesn't enforce typing (which you'll have to deal with explicitly in Java) and doesn't limit the fields to only those from the database.
If all the database values are strings, things get cleaner as no casts are necessary.
List<Map<String, String>> myData
tempName = myData.get(i).get("name");

Categories

Resources