How to change an array into an ArrayList? (generics) - java

I have a task to change a type of a variable into ArrayList and I need to initialize it as an ArrayList. I don't know how to do it :(
I tried this in a such way:
private ArrayList<T> warehouseContent = new ArrayList<T>();
public void registerProducts(Product... products) {
WarehouseItem[] updatedWarehouseContent = new WarehouseItem[warehouseContent.size()
+ products.length];
int i = 0;
for (; i < warehouseContent.size(); i++) {
updatedWarehouseContent[i] = warehouseContent[i];
}
for (; i < updatedWarehouseContent.length; i++) {
updatedWarehouseContent[i] = new WarehouseItem(products[i - warehouseContent.size()]);
}
warehouseContent=updatedWarehouseContent;
}
But I think it isn't correct. The source code which I need to change is below:
private WarehouseItem[] warehouseContent = new WarehouseItem[0];
public void registerProducts(Product... products) {
WarehouseItem[] updatedWarehouseContent = new WarehouseItem[warehouseContent.length
+ products.length];
int i = 0;
for (; i < warehouseContent.length; i++) {
updatedWarehouseContent[i] = warehouseContent[i];
}
for (; i < updatedWarehouseContent.length; i++) {
updatedWarehouseContent[i] = new WarehouseItem(products[i - warehouseContent.length]);
}
warehouseContent=updatedWarehouseContent;
}
Could someone give me any tips or explain me what I need to use here a generic type ArrayList?

Start by declaring the warehouseContent type as a list of WarehouseItem:
private List<WarehouseItem> warehouseContent = new ArrayList<>();
Now you can rely on ArrayList's built-in ability to grow in your registerProducts method:
public void registerProducts(Product... products) {
for (Product product : products) {
warehouseContent.add(new WarehouseItem(product));
}
}
This one loop does what the two loops and an allocation of your original implementation did. Note that copying the content of an old array into the new one is still there, but it is encapsulated in the add method of ArrayList.

Related

get an object based on its static value

I am initalizing several objects of the same type that have a common field:
public class Example {
private static objectCounter = 1;
public Example () {
objectCounter++;
}
}
Since these objects are created with a for loop like this
for (int i = 0; i<5; i++) {
Example e = new Example();
}
they are not referenced.
Is there a way to get a specific object based on objectCounter value ?
Something like
//get the Example object with objectCounter==2
get(2);
Thank you
My suggestion will be saving into array:
Example store[] = new Example[5]
for (int i = 0; i<5; i++) {
store[i] = new Example();
}
And then , search for the specific object.
As stated in the comments, a static value will persist through all instances of your class.
If you want your Example to "know" it's identity, pass it in when you construct it:
Example:
public class Example {
private int id;
public Example (int val) {
this.id = val;
}
// Getters/setters
}
Probably also want to add your objects to a list to access them later, so before your for-loop:
List<Example> examples = new ArrayList()<Example>;
And create them like this:
for (int i = 0; i<5; i++) {
Example e = new Example(i);
examples.add(e);
}

Generic Array List [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I need to create an array list using generics. My add method seems to work sometimes, however my get method appears to have a good amount of problems and i don't receive a compile error. However when i try to get an object from the Array list using my get method it throws a java out of bounds exception. here i what i have so far, and i am using BlueJ. Also, the instructions were to set the initial "illusion" length to zero.
public class AL <X> {
private X[]data;
private int count;
public AL() {
count = 0;
data = (X[]) new Object[0];
}
public void add (X v) {
if (data.length != count) {
data[count] = v;
count++;
} else {
X [] newdata = (X[]) new Object[data.length * 2];
for (int i = 0; i < data.length; i++) {
newdata[i] = data [i];
}
count++;
data = newdata;
}
}
public X get(int index) {
if (index >= count || index < 0) {
throw new ICantEven();
} else {
return data[index];
}
}
}
Your add method doesn't work, since the initial backing array you are using has a 0 length, which remains 0 even when you try to double it (since 0*2==0).
You also forgot to actually add the new element when you resize the backing array. If you hadn't forgot that, you'd get the exception in add.
First of all, change the initial size of the array created by your constructor to be positive :
data = (X[]) new Object[10];
Then add
data[count] = v;
to the else clause of your add method (just before count++;).
Your add method can be further simplified :
public AL()
{
count = 0;
data = (X[]) new Object[10];
}
public void add (X v)
{
// resize backing array if necessary
if (data.length == count)
{
X [] newdata = (X[]) new Object[data.length * 2];
for (int i = 0; i < data.length;i++ )
{
newdata[i] = data [i];
}
data = newdata;
}
// add new element
data[count] = v;
count++;
}

Creating an Array List from scratch

I was wondering if anyone would be able to point me in the correct direction in regards to creating my own array list methods. For instance, the current project I am assigned to does not allow for me to use the methods given to me for free like in the following example.
package com.tutorialspoint;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// create an empty array list with an initial capacity
ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
// use add() method to add elements in the list
arrlist.add(15);
arrlist.add(22);
arrlist.add(30);
arrlist.add(40);
// adding element 25 at third position
arrlist.add(2,25);
// let us print all the elements available in list
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}
}
}
This example shows the add() method. For my project I have to create this method myself and call it from a different file within my package.
I find this as an interesting problem. I am always curious about how things work at the raw level.
If you think about it, an ArrayList is basically just an array that you can expand. So you can either have a really big array (which would take a lot of memory for one ArrayList) or every time you add something, you make a new bigger array and copy the contents and add the new item (which I think the performance is O(N)).
This is my attempt without using any libraries:
public class MyArrayList<T>
{
private T[] asArray;
#SuppressWarnings("unchecked")
public MyArrayList()
{
asArray = (T[]) new Object[0];
}
public void add(T t)
{
#SuppressWarnings("unchecked")
T[] temp = (T[]) new Object[asArray.length + 1];
// copy everything over to the new array
for (int i = 0; i < asArray.length; i++)
{
temp[i] = asArray[i];
}
// add the new element
temp[asArray.length] = t;
asArray = temp;
}
public void remove(int index)
{
if (index < 0 || index >= asArray.length) return;
#SuppressWarnings("unchecked")
T[] temp = (T[]) new Object[asArray.length - 1];
boolean found = false;
// copy everything over to the new element
for (int i = 0; i < asArray.length; i++)
{
// don't copy if the indices are the same
if (i == index)
{
found = true;
continue;
}
temp[i - (found ? 1 : 0)] = asArray[i]; // it's i - 1 after the removed object so then it doesn't leave a gap and it doesn't go over the array's length
}
asArray = temp;
}
public T get(int index)
{
return asArray[index];
}
}
I am quite proud of this code. :) I consider Short_Teeth's code cheating because the class is a subclass and, well, doesn't add anything. I hope I helped.
This is very easy to understand; However, I explained a little bit in comments.
public class MyArrayList<E extends Object> {
private static int initialCapacity = 5;
private static int currentSize;
private Object[] myArrayList = {}, temp = {};
private static int currentIndex = 0;
public static void main(String[] args) {
MyArrayList arrList = new MyArrayList();
arrList.add("123"); //add String
arrList.printAllElements();
arrList.add(new Integer(111)); //add Integer
arrList.printAllElements();
arrList.add(new Float("34.56")); //add Integer
arrList.printAllElements();
arrList.delete("123");
arrList.printAllElements();
arrList.delete(123);
arrList.printAllElements();
arrList.delete(123);
arrList.printAllElements();
}
public MyArrayList() { //creates default sized Array of Objects
myArrayList = new Object[initialCapacity]; //generic expression
/* everytime I cross my capacity,
I make double size of Object Array, copy all the elements from past myObject Array Object
*/
}
public MyArrayList(int size) { //creates custom sized Array of Objects
myArrayList = new Object[size];
}
public void add(Object anyObj) {
//add element directy
myArrayList[currentIndex] = anyObj;
currentSize = myArrayList.length;
currentIndex++;
if (currentIndex == currentSize) {
createDoubleSizedObjectArray(currentSize);
}
}
//print all elements
public void printAllElements() {
System.out.println("Displaying list : ");
for (int i = 0; i < currentIndex; i++) {
System.out.println(myArrayList[i].toString());
}
}
private void createDoubleSizedObjectArray(int currentSize) {
temp = myArrayList.clone();
myArrayList = new MyArrayList[2 * currentSize]; //myObject pointer big size data structure
// myObject = temp.clone(); //probably I can do this here as well. Need to check this
System.arraycopy(temp, 0, myArrayList, 0, currentSize);
}
void delete(Object object) {
//if already empty
if (currentIndex == 0) {
System.out.println("Already empty!");
return;
}
//you don't need to delete anything. I can simply override the storage
currentIndex--;
}
}
import java.util.ArrayList;
public class MyArrayList<E> extends ArrayList<E>{
private static final long serialVersionUID = -5164702379587769464L;
public void newMethod(){
// No implementation
}
}
This is a class which extends from ArrayList and a method called newMethod() was added to this class.
Below we are calling this newly created method in your case you must implement the add to this newly created method.
public class Hello {
public static void main(String args[]) {
MyArrayList<Integer> myList = new MyArrayList<Integer>();
// It has the ArrayList add() method as this new class extends from ArrayList (all the ArrayList methods are included)
myList.add(2);
// The newly created method in your case you need to implement the add yourself
myList.newMethod();
}
}
This could also be a good link for what you need.
http://www.java2novice.com/java-interview-programs/arraylist-implementation/
I also recomend that you try to implement and solve your problems first and then ask questions about a specific problem, and only after you done a good research about what may be causing this problem (There are lots of resources out there). If you done some research before you asked this question, I'm pretty sure that you would have been able to solve everything on your own.
Hope you find this information useful. Good luck.

Adding objects to an array

I have been looking at questions of how to add elements to an array How can I dynamically add items to a Java array?.
I do not understand how to add objects of a class type, not a datatype like String. How am I supposed to do this, when the object patient has various datatypes? What I can't get my head around, is how to put the attributes of a Patient object into an array.
Class Patient{
public Patient(String ptNo, String ptName, int procType) throws IOException
{
Patient.patientNo = ptNo;
Patient.patientName = ptName;
Patient.procedureType = procType;
}
}
Another class:
public static void main(String[] args) throws IOException
{
Patient [] patients;
Patient p = new Patient(null, null, 0);
int i = 0;
for (i = 0; i < 2; i++)
{
patients.add(p);
}
}
I understand I am missing the obvious, and only come here, after exhausting other resources.
You need to specify the array size like below
Patient [] patients = new Patient[2];
Then now add the elements like below
patients[i] = new Patient(null, null, 0)
The complete code like below
for (int i = 0; i < 2; i++)
{
patients[i] = new Patient(null, null, 0);
}
You need to access an array using the indexes
patients[i] = p;
but before that you need to initialize it as well.
Patient [] patients = new Patient[10]; // random init
Since you want them to be dynamic, try to use an ArrayList and keep adding the objects to it.
List<Patient> patients = new ArrayList<>();
patients.add(p);
Arrays are accessed via index:
Please modify your code like this.
public static void main(String[] args) throws IOException
{
Patient [] patients = new Patient[10];
Patient p = new Patient(null, null, 0);
int i = 0;
for (i = 0; i < 2; i++)
{
patients[i] = p;
}
}
You are using an array and not an ArrayList thus add them by specifying the index
for (i = 0; i < 2; i++)
{
patients[i] = p;
}
EDIT
If you really want to assign the same object in the string you can even skip the object reference, like
public static void main(String[] args) throws IOException
{
Patient [] patients = new Patient[2];
int i = 0;
for (i = 0; i < 2; i++)
{
patients[i] = new Patient(null, null, 0); // No need for p now
}
}
First you need to initialize an array to be of a specific size.
Patient [] patients = new Patient[2];
Secondly, you need to use index when assigning a value.
patients[i] = p;
Finally;
public static void main(String[] args) throws IOException
{
Patient [] patients = new Patient[2];
for (int i = 0; i < patients.length; i++)
{
patients[i] = new Patient(null, null, 0);
}
}
First:
Some fixes:
class Patient
{
public String patientNo;
public String patientName;
public int procedureType;
public Patient(String ptNo, String ptName, int procType)
{
this.patientNo = ptNo;
this.patientName = ptName;
this.procedureType = procType;
}
}
Since you want your patients to be unique not the same as Patient.sth is class' property (common to all instances).
Now array and inserting:
Patient patients[] = new Patient[2];
for (int i = 0; i < patients.length; i++)
{
patients[i] = new Patient(null, null, 0);
}
but again do not fill array with the same objects. In addition not to be bound to fixed array size - use Vector (for example)
Update: about class members / aka static object members
These 2 code samples are completely different things:
class X
{
public String abc;
public void someMember()
{
this.abc = ;
}
}
and
class X
{
public static String abc;
public void someMember()
{
X.abc =
}
}
You must distinguish between what is unique to an abject and what is common to a class (ie available to all instances - common to them).
With static keyword you declare class members (they will be common foa all instances). You cannot use them with 'this' keyword which is reserved for instance members from the first example.
Here is what you must read class vs instance members

Java array NullPointerException

The code block is listed below:
public static Vertex[] computeSubGraph(Vertex[] AdjList, int[] retiming)
{
Vertex[] subGraph = new Vertex[AdjList.length];
for (int i = 0; i < AdjList.length; i++) {
System.out.println(i);
subGraph[i].nodeDelay = AdjList[i].nodeDelay;
subGraph[i].predecessor = AdjList[i].predecessor;
subGraph[i].mark = AdjList[i].mark;
subGraph[i].starTime = AdjList[i].starTime;
subGraph[i].finishTime = AdjList[i].finishTime;
for (int j = 0; j < AdjList[i].inArcList.size(); j++) {
ArcNode old = AdjList[i].inArcList.get(j);
ArcNode newNode = new ArcNode(old.adjVex, old.arcWeight);
subGraph[i].outArcList.add(newNode);
subGraph[old.adjVex].inArcList.add(newNode);
}
}
return subGraph;
}
This is the Vertex class:
public class Vertex implements Comparable<Vertex> {
public int arcWeight;
public int preDelay;
public boolean infinite = true;
public int nodeDelay = 0;
public Vertex predecessor = null;
public ArcNode firstArc = null;
public int mark = 0;
public int starTime;
public int finishTime;
public ArrayList<ArcNode> inArcList = new ArrayList<ArcNode>();
public ArrayList<ArcNode> outArcList = new ArrayList<ArcNode>();
}
Actually, I just want to copy the element in AdjList to a new array subgraph. But the error message shows that "java.lang.NullPointerException" and shows the problem lies in "subGraph[i].nodeDelay = AdjList[i].nodeDelay;" line.
I tested by printing to the console. And found the AdjList.length is 8 and the problem occurs in the very first round; And even when I only write "subGraph[i].nodeDelay;" without assigning any value to it, it also shows the wrong message.
Any idea on this? Thanks in advance.
Add it inside the loop:
subGraph[i] = new Vertex();
You first need to instantiate an object (subGraph[i] in your case) before accessing it.
The answer is: uninitialized variable. You did initialize subGraph to be an array, but you did not initialize subGraph[i].
When you create an object array in java, it's automatically initialized with null values. It's your responsibility to loop on the array an populate it with references to new objects.
In your case, you should assign Vertex objects to all array positions.
You need to create a Vertex instance and place it in the array prior to setting any fields.
Something like:
public static Vertex[] computeSubGraph(Vertex[] AdjList, int[] retiming)
{
Vertex[] subGraph = new Vertex[AdjList.length];
for (int i = 0; i < AdjList.length; i++) {
subGraph[i] = new Vertex(); // adding instance prior to setting fields.
System.out.println(i);
subGraph[i].nodeDelay = AdjList[i].nodeDelay;
subGraph[i].predecessor = AdjList[i].predecessor;
subGraph[i].mark = AdjList[i].mark;
subGraph[i].starTime = AdjList[i].starTime;
subGraph[i].finishTime = AdjList[i].finishTime;
for (int j = 0; j < AdjList[i].inArcList.size(); j++) {
ArcNode old = AdjList[i].inArcList.get(j);
ArcNode newNode = new ArcNode(old.adjVex, old.arcWeight);
subGraph[i].outArcList.add(newNode);
subGraph[old.adjVex].inArcList.add(newNode);
}
}
return subGraph;
}
On add
subGraph[i] = new Vertex();
before this line
subGraph[i].nodeDelay = AdjList[i].nodeDelay;
Because subGraph[i] is initially null . So subGraph[i].nodeDelay will obviously throw a NullPointerException, because you are trying to access or modify the field of a null object. Array of references will always be initialized with elements of null references by default.

Categories

Resources