What is the best way to store an element that has multiple elements? As in a 6d array.
I have seen something along the lines of ArrayList(ArrayList(ArrayList(ArrayList))), but don't have a clue as to how or mostly why it would be configure as such or how to access the elements!
As an example, I want to create an array(list) that stores the following information:
house id, house number, street name, residents, owner first name, owner last name
I would like to be able to sort and search on anyone of the sub-elements in the main record element.
What I have done is create an arraylist that contains an arraylist for each of these. Basically I have a class called HouseArray that has a method called CreateArray. From my class GUI, I have
houses = new HouseArray();
houses.CreateArray();
In class
HouseArray, my method CreateArray has
ArrayList<Integer> entryID;
ArrayList<Integer> houseNum;
ArrayList<String> streetName;
ArrayList<Integer> residents;
ArrayList<String> firstName;
ArrayList<String> lastName;
entryID = new ArrayList();
houseNum = new ArrayList();
streetName = new ArrayList();
residents = new ArrayList();
firstName = new ArrayList();
lastName = new ArrayList();
and then I use an AddEntry method that puts data into each arraylist.
this.entryID.add(12345);
this.houseNum.add(9876);
this.streetName.add("My Street");
this.residents.add(4);
this.firstName.add("John");
this.lastName.add("Jones");
I am at a loss at how I would be able to sort this mess and keep the entries synchronized without manually writing a lot of coding to do it all. Also, I want to be able to sum the number of residents that live on a particular streetName or total the number of residents that live in houses owned firstName or lastName.
Am I on the right track or is there a better way to do this?
Teaching myself java, so not sure if this counts as homework.
As an example, I want to create an array(list) that stores the
following information:
house id, house number, street name, house color, owner first name,
owner last name
the best approach is to create a Class name it House and have these attributes as its state.
class House {
private long houseId;
private long hNo;
private String streetname;
private String color;
private String owner;
private String firstName;
public House(long houseId, long hNo, String streetName, String color, String owner, String firstName){
//initialize your instance variables here
}
public void setHouseId(long houseId){
this.houseId = houseId;
}
//do the same thing for reamining attributes
//getters and setters for all the attributes.
}
now, create a java.util.List which holds House Object.
List<house> houseList = new Arraylist<>();
//and populate the list with house objects.
House house1 = new House(123,223,"Bond Street", "Green","James Bond", "James");
list.add(house1);
This approach is more Object-Oriented way of doing things, as House represents an Object which has state and behaviour.However, if you want to sort your House elements in your arrayList you will have to override equals and hashcode methods.
I think another approach would be create House class with those properties.
Instantiate house object and add to arraylist. You may override equals and hashcode method to perform sorting.
Example:
class House{
int houseNum;
String street;
...
//get/set for above properties.
}
And add it to list:
House houseObj = new House();
list.add(houseObj);
Where exactly have you seen along the lines of ArrayList(ArrayList(ArrayList(ArrayList)))?? This looks wierd. Never have such kind of design..
If you want to store multiple fields, then create a custom class with all those fields, and have an ArrayList of that class.
For e.g: -
class House{
private int houseId;
private int houseNumber;
private String streetName;
private String owner;
private String firstName;
// Constructors
// Getters and Setters
}
And create an ArrayList of that class: -
List<House> myHouses = new ArrayList<House>();
then, to add an object to your list, just use normal add method: -
myHouses.add(new House(houseId, houseNumber, ....));
And to access elements: -
for (House myHouse: myHouses) {
System.out.println(myHouse.getHouseNumber());
}
I think you're not just new to Java. You're new object-oriented programming in general. Are you a student and this is some sort of homework? If it is, please tag it as such.
For your particular data, your class should be House.
public class House
{
int entryId;
int houseNum;
String streetName;
String houseColor;
String firstName;
String lastName;
}
Note that in my sample code above, I'm assuming you know enough of java to add the access modifiers like private, public, etc. and know enough about how to add getter and setter methods, (e.g. getEntryId(), setEntryId(int entryId), etc.).
If your objects are actually more complex, you might also be better off creating classes like Address, Person, etc.
Then with this class, you do create a list:
List<House> houses = new ArrayList<House>();
House myHouse = new House();
// insert whatever data you want into "myHouse"
houses.add( myHouse );
To sort the objects in a list, because it's in a List, it's part of Java's Collection Framework. You can use the Collections.sort() method to sort it. But first you need to understand how it works.
I would suggest you the following pages:
Object-Oriented Programming Concepts
Java Tutorial: Collections
Object Ordering
I am at a loss at how I would be able to sort this mess
First, others have already pointed out that you should create a House class to organize "this mess".
To sort it, implement the Comparator interface, e.g. (assuming your House class has a getEntryID method):
public class HouseIDComparator implements Comparator<House> {
#Override
int compare(House house1, House house2) {
return house1.getEntryID().compareTo(house2.getEntryID());
}
}
This comparator can be passed to Collections.sort(List<T>, Comparator<? super T>) for sorting. (Note that there is also a sort method with one argument, for lists of types that implement the Comparable interface. However, you probably do not want your House class to implement that, since it is not obvious on what basis houses should be compared, and you yourself might want to use several different ones.)
As for summing up values, the best way is to loop over all elements in the list and sum up manually.
Related
I'm currently doing an intro level undergrad CS course (learning basics of 'program'&'class' building using Java).
The relevant part of my personal (&job related) project: I have a list of zip codes associated with One county.
I'm gonna define a class called 'County'. Then I'm gonna use this class to construct an object of type County, called 'middlesex'.
ie: County middlesex = new County();
Now, in this object, I want to construct a number of objects of class-type ZipCode.
ie: ZipCode objName = new ZipCode();
(Each such ZipCode object is gonna contain certain instance data).
My problem is this. Assume that I don't know how many zipcodes are contained in the Middlesex county. However, I have a .txt file that contains just a list of all the zipcodes of Middlesex county.
Let's say there are n number of zipcodes in this list.
In the object 'middlesex', of class-type 'County', I want to set up a loop. This loop will scan each zipcode in the list, then construct an object of class-type ZipCode for each zipcode.
Thus the loop may go thru n iterations, and construct n objects of type ZipCode.
Thus, for every iteration of the loop, a unique object-reference-name must be created (corresponding to the particular zipcode in the list).
Part of this problem (but distinct and optional), is that I want to know how (if possible), I can set up a structure that allows an inputted (scanned) string to be used as the name of an object-reference.
I apologize if I've made incorrect terminology use. I know that many are gonna suggest arrays. I haven't learned about them yet, but I gotta read about them over this weekend for school. I'm just gonna try to figure this out for a day or two, and then just move on to using arrays to perform this task.
So, if I've made any sense to anyone, is what I'm trying to do possible without arrays?
Thank u.
You're describing a very basic scenario, one where one object contains (possibly) many references to objects of a 2nd type, what we call a constructor called "composition" where the relationship here is a "has-a" relationship, County has-a (or has-many) zip codes
As opposed to using inheritance to wrongly try to solve this, the "inheritance" relationship or the "is-a" relationship -- County is not a zip code and zip code is not a county.
The code to create this can be very simple, something like:
import java.util.ArrayList;
import java.util.List;
public class County {
private String name;
private List<String> zipCodes = new ArrayList<>();
// constructor that takes county name
public County(String name) {
this.name = name;
}
public void addZipCode(String code) {
zipCodes.add(code);
}
// ..... more code
If a zip code is a single String, then no need to create a new class for this. If however it is more complex and holds more data than a single String, then create a class for ZipCode, and change the code above to something like
import java.util.ArrayList;
import java.util.List;
public class County {
private String name;
private List<ZipCode> zipCodes = new ArrayList<>();
// constructor that takes county name
public County(String name) {
this.name = name;
}
public void addZipCode(ZipCode code) {
zipCodes.add(code);
}
// getters, setters, a decent toString method override...
Where ZipCode could contain....
public class ZipCode {
String code;
// other fields if needed....
public ZipCode(String code) {
this.code = code;
}
// ....
then when reading in data, create your County objects and as each Zip code is read in, add it to the appropriate County object using the addZipCode(...) method.
zipCode is an object of Type ZipCode then what are its fields? Think of the reasons for making it an object and not a variable
"Thus the loop may go thru n iterations, and construct n objects of type ZipCode"
Unforutnality this is not possible without making the use of Arrays
"structure that allows an inputted (scanned) string to be used as the name of an object"
Nope can do that.
So Let's say I have a List of Persons that are related to each other and each contains their own family tree.
public class Person {
private int id;
private String name;
private List<Integer> ancestorIds;
private int parentId;
//getters and setters
}
so let's say I have the list as following:
List<Person> persons = new ArrayList<Person>();
persons.add(new Person(3,"grandpa", {}, null));
persons.add(new Person(4,"pa", {3,4},3));
persons.add(new Person(5,"uncle", {3,5},3));
persons.add(new Person(7,"me", {3,4,7},4));
But now we know that my grandpa his father was actually the one with id 1.. And i need to update the list.. How can I do this keeping in mind that I need to update it by line.. So first my grandpa.. Then taking the ancestorids list of him and give it to my pa and uncle (adding their ids as well). and then me taking the list of my pa and adding me. I think I need some recursive method for this.
Thanks in advance
If you make changes on this data structure it would be more flexible if you let each person point to it's direct ancestor only. And then build the tree on demand.
The way you mentioned in your question I would use if the tree don't gets changed.
Are you forced to use this representation? It would make more sense for the family tree to reference Persons, in particular, for the Person class to be defined as:
public class Person {
private int id;
private String name;
private List<Person> ancestors;
private int parentId;
//getters and setters
}
If done in this way, you don't need to update anything, except for your great grandfather. In fact, doing it line-by-line isn't a robust solution, since there's room for error (if you miss a single ID), and you should avoid this, to have good design. Even worse, unless you keep backpointers (i.e. have descendants as well as ancestors), there is no efficient way to update ancestors down the tree.
Hey guys ive read everything and i still cant get it. your my last hope.
All i need is a multidimensional arraylist that can store both a string and number at the same time. Please help.
What are the information you want to store? What do they represent? I doubt you just want to store some number and some string without context. Find out what the context is, what they represent, then extract a class.
Is it a student's name and age?
class Student {
private int age;
private String name;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
...
}
Is it a car manufacturer and production year?
class Car {
private int productionYear;
private String manufacturer;
...
}
Once you've extracted your class, you can just create an ArrayList of your type, something like this:
ArrayList<Car> cars = new ArrayList<Car>();
cars.add(new Car("Toyota Avalon", 2014));
cars.add(new Car("Fiat Focus", 1982));
The only way to do that would be to have the list contain Object, and then check the type of objects after you pull them out.
There is almost certainly a better architecture though (separate lists, maybe using a map, maybe storing an object that itself contains both a number and a string) etc. Unfortunately you haven't given enough information to let us give any guidance on that...
For my homework, we've been tasked with creating:
Person class with variables firstName, lastName, streetAddress, zipCode and phone.
CollegeEmployee extends Person and adds ssn, salary, and deptName.
Faculty extends CollegeEmployee by adding a boolean tenure.
Last but not least, Student extends person by adding GPA and major.
Everything looks good displaying to screen, and I'm moving on to the next part of the assignment which is to create 14 records (7 students, 4 employees and 3 faculty) in an array.
3 different classes, with multiple data types, and I cannot for the life of me figure out how to populate an array with this. This is the first array I've created that's not been completely integer. The Java Tutorials didn't give me anything, and while Java: Generic Static Multidimensional Arrays has some great information, it's a little more than I can wrap my head around right now.
I'd initially thought of creating array[14][10] -- fourteen variables each for ten objects -- but I can't mix data types. That's where I got lost.
Anyone have any suggestions on how to design this array and be able to display the values from it afterward?
Any hints and suggestions would be appreciated!
Thanks.
From what I understand, no need to get fancy with multi-dimensional arrays.
1) Create an array that takes Person instances.
Person [] myPeeps = new Person[14];
2) Create a print method on Person, which subclasses override to print the relevant info.
Because your array expects Person instances, you can put instances of any subclasses of Person, because subclasses always have an is-a relationship with their superclass.
Because Person has a print method, you can call print on anything you pull out of the array. Subclasses provide their own implementations so they can print their relevant data. That way, you don't really care about which subclass any particular instance is; the correct print implementation for the instance is invoked at runtime.
You don't need a multidimensional array. You can make an array of Person objects.
Person[] people = new Person[14];
people[0] = new Student();
people[1] = new Employee();
.
.
.
You could also create a Person[] array, just as you would an int[] array. e.g.
Person[] people = new Person[14]
You can then add people to the Array like this:
people[0] = new Student();
people[1] = new CollegeEmployee();
people[2] = new Faculty();
If you want to check what type of person is in each index you will want to use instanceof. Try looking here for more help
One example of using instanceof is:
if(people[0] instanceof Student){
System.out.println("This person is a student");
}
Or try using generics.
You could create an ArrayList<Person> and can then add any type of person to this ArrayList.
e.g.
ArrayList<Person> peopleList = new ArrayList<Person>();
//People can be added like this
peopleList.add(new Student());
peopleList.add(new CollegeEmployee();)
Again you are able to use instanceof to check which type of person is in each index!
Also if you never write
Person person1 = new Person();
In your code then consider making your class abstract.
To start:
Person[] myArray = new Person[14];
This is essentially why object oriented programming is so wonderful. If you'll notice, all Faculty, CollegeEmployee, and Student are a subset of type Person. Because of this, you can have them all contained in the same dataset if it is declared as type Person.
Person[] array = new Person[14];
You can add all of your objects to that array; however, be careful. When you go to use the elements of the array Java now only knows that each has the methods that a Person does - so therefore you can only make use of firstName, lastName, streetAddress, zipCode, and phone from these elements unless you cast the objects after they are retrieved.
Since they are all of type Person, why not use a Person array?
Person [] people = new Person[14];
You can safely add all types of Person to this array, however you can only treat them as Person (without casting). To have each subclass output customized details, and add this method in Person
class Person {
void print() {
// default Person printing
}
}
and override this method in each subclass to print its member variables:
class Student extends Person {
void print() { // <-- note same method signature!
// print "I'm a Student", GPA, major
}
}
and when the array is populated:
for (Person p : people) {
p.print(); // delegates to print method associated with the underlying type
}
Check out the inheritance tutorial
The class Person is a common superclass to all the types of the objects you want to store in the array. You can create the array based on that common supertype. Then you can access methods that are defined in that tpe on all elements of the array, regardless of the actual type -- the behavior is as defined in the actual type (look up inheritance for java if this is not clear).
If you need specific behavior based on the actual type, you need to cast the array element to the concrete type (you can determine it using instanceof, for example)
Ive been trying to work this out for a few hours now, but am stuck, hence I am coming here for some help.
N.B. I am using BlueJ, to construct these classes, as im still learning.
What I am trying to do is create a PlayList which has a two parameters: name and a ArrayList of tracks.
It then creates a playlist and copies the tracks from the list (in order) onto the playlist; but I dont want any help with this part, as of yet.
My issue is I am unsure how to call the ArrayList when constructing the PlayList.. Because the specified type is of .
public class PlayList
{
private String myName;
private ArrayList<Track> myTracks;
private int myDuration;
public PlayList(String name, ArrayList<Track> tracks) {
name = myName;
myTracks = new ArrayList<Track>();
for (Track t : tracks) {
myTracks.add(t);
}
}
}
What happens, in BlueJ, is when I construct a new PlayList class, it provides an empty field box for String name, and for ArrayList tracks. String name is fine, as I can simply put "anything" but am stuck as to the ArrayList tracks?
I know this is probably isnt a very specific question, but I am still learning.
sunadorer's response should answer your direct question. I have some general remarks about naming conventions for the fields in your class and the parameters of your constructor.
I would not prefix your fields with 'my'. It is a bit of a matter of style, but I would not have much against using the same names for the constructor parameters. You can distinguish between the parameter and the field by using this.name when referring to the field.
Also, using ArrayList here seems unnecessarily restrictive: you could use the more general List interface (which ArrayList is just one implementation of, so you don't have to touch PlayList if you want another kind of List later o):
public class PlayList {
private String name;
private List<Track> tracks;
private int duration;
public PlayList(String name, List<Track> tracks) {
this.name = name;
this.tracks = new ArrayList<Track>(tracks);
}
}
The constructor of your PlayList wants an object of type ArrayList filled with elements of type Track. So to create a PlayList you must provide an already created one.
It depends on your surrounding of the call, maybe you already build a list there and can just put it into your PlayList constructor, but you need something like this anywhere:
// Create an empty list
ArrayList<Track> tracks = new ArrayList<Track>();
// Add a track. e.g. when receiving a gui event
tracks.add(track); // track was created with new Track()
Or maybe you don't need/want lists outside of PlayList objects. You could use PlayList objects to manage and encapsulate those, by changing the constructor to only create an empty list on its own and allow others to add tracks to it via an addTrack method.