How do i use multidimensional arraylist? - java

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...

Related

create multiple instances of a class without array in a loop

I know this question been asked many times, and I've looked through many similar topics but they all include array or list and I don't want to use array or lists, second I don't understand :).
Anyway here's my question: I have a class with name,id,job methods to store these in a variable, and I want to to ask how many Staff the company has, and that's why I cant hard code each variable because the number is unknown thus I need a loop, And am not allowed to use array or list. Any idea or help is appreciated Thanks.
Here's the code for the class:
public class Staff{
public void name(String name){
String staff_name = name;
}
public void id(String id){
String staf_id = id;
}
public void job(String job){
String staff_job = job;
}
}
code for main:
import javax.swing.JOptionPane;
public class P2Q2{
public static void main(String[]args){
System.out.println("How many staff in Department? ");
String staff_num = JOptionPane.showInputDialog(null,"How many Staff are there",
"Department staff numbers",JOptionPane.QUESTION_MESSAGE);
int staff_num_int = Integer.parseInt(staff_num);
for(int i=1;i<staff_num_int;i++){
//somthing in here to create objects for each staff
}
}
}
Here is the whole question:
EDIT:
I just didn't want to provide the whole question, but if this is better there you go.
You can create Staff objects without array or list - but it will not have sense because you will not have access to the objects. If you will not have access to the objects - that means the Garbage Collector will destroy them after you go out the loop scope.
Well if you can't use an array or list, and you want to access to each staff object. You can look into using something such as a hash map. You can store objects in the hash map and just use the staff names as a key to access each object after created and added to the map.

Empty array object creation in Java

I am trying to learn some foundational ways to manipulate certain aspects of coding that stray away from single use and make something more "dynamic" that can kind of build itself on the fly.
For example of what I would like to accomplish, which I believe would consist of using some type of empty array of an object and a loop. I just don't know how to write it.
Lets keep it basic and say I have a Person Class.
public class Person
{
String name;
String age;
}
So in my TestDrive I would just get a simple user input to gather information on that person.
Such as...
import javax.swing.JOptionPane;
public class PersonTestDrive
{
public static void main(String[] args)
{
String name;
String age;
name = JOptionPane.showInputDialog(null, "Enter your name");
age = JOptionPane.showInputDialog(null, "Enter your age");
Person human = new Person();
human.name = name;
human.age = age;
JOptionPane.showInputDialog(null, "Would you like add another entry?");
/* At this point it would loop if the user wanted to add another entry.
I would just wrap it all in while loop that just checked if the user said yes or no.
However, if they do choose to add another entry
"IF" a human object already existed it would create a
new human2 object, and then human3, etc. */
}
}
It sounds that all you need is a collection of objects, such as ArrayList<Person>.
"human" is a name of your variable, and at compile time you don't know how many other variables there can be so you cannot refer to them in the code using "human2", "human3" and so on. You can create these variables, but they may be nulls and your input will also be limited to how many variables you have. Another problem would be keeping track of what variable to assign to next.
With List<Person> list you can do list.get(2) to get third object (it will thrown an exception if there are few than 3) or list.size() to check how many objects were created so far.
Here is some more information about Java collections: http://docs.oracle.com/javase/tutorial/collections/

Is there an easy way to sort an arraylist in this manner?

I'm wondering if there is a way to sort an Arraylist of custom objects to fit the situation explained below? I'm assuming I'll have to write a custom comparator.
Let's say I have an object class that looks like this:
public class Person {
private String status; //options: Online, Away, Offline
private String name; //Person's name
private Date date; //Last signed on
//basic constructor
public Person() {
//set default values
}
//constructor to set all variables
public Person(String s, String n, Date d) {
status = s;
name = n;
date = d;
}
//setters & getters for each of the fields
}
Sorting based on name and date should be fairly easy. However, I'm wondering how I would sort based on the status? I would like to be able to sort my array based on whether the person is currently online and also who is offline. I'm not too concerned with who is away.
The above class is just an example class. My actual class has a JLabel set an icon based on the status. The setText() remains unused. I thought of a possibility of setting the label to values of 0, 1, and 2 and just using a typical integer comparator but I wasn't sure if that was an advised way of doing it.
Surely I'm missing an obvious solution here, so perhaps a comment or link can provide the necessary information. I know there are tons of 'Sort Arraylist' threads here at SO and I've browsed a lot of them. Most of them are just sorting Strings alphabetically or Integers though.
if i understand correctly you basically want to sort on 2 fields - the major field is status (so people of the same status are bunched together) and then, whithin each gruop of people with the same status, by name.
a comparator that does this looks like this:
public class CompositePersonComparator implements Comparator<Person> {
#Override
public int compare(Person a, Person b) {
//1st and foremost - see if they are not of the same status.
int statusComparison = a.getStatus().compareTo(b.getStatus());
if (statusComparison!=0) return statusComparison;
//logical else - same status, sort by name
return a.getName().compareTo(b.getName());
}
}
Using enums can be useful here
enum MyEnum { ONLINE, AWAY, OFFLINE;}
I suggest we handle the status as an enumerated data type instead of a String where it can only be one of a few strings. This makes it easy to write a readable compareTo method:
public class Person implements Comparable<Person> {
private Status currentStatus;
private String name; //Person's name
private Date date; //Last signed on
enum Status {ONLINE, AWAY, OFFLINE};
//basic constructor
public Person() {
//set default values
}
//constructor to set all variables
public Person(Status s, String n, Date d) {
currentStatus = s;
name = n;
date = d;
}
/**
* Order the Persons first by status where all ONLINE Persons are listed first.
*/
#Override
public int compareTo(Person other) {
if(other.currentStatus == currentStatus)
return name.compareTo(other.name);
return currentStatus.ordinal() - other.currentStatus.ordinal();
}
}

Storing elements that have multiple elements

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.

Help constructing a class with ArrayList as a parameter

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.

Categories