How to pass a linked list in Java? - java

I am having trouble understanding how to pass a linkdlist into a method that display that list as a stack. I am aware i havent specifed the type of list but my instructor said that it would not matter for this purpose. but I am still learning so I'm not to sure if I am passing the linkedlist correctly into the method.
import java.util.LinkedList ;
import java.util.ListIterator;
public class UseStacksAndQueues{
public static void main(String[] args) {
StacksAndQueues sQ = new StacksAndQueues();
String [] days = {"mon","tue","wed","thur","fri", "sat","sun"};
LinkedList aList = new LinkedList();
LinkedList newList = new LinkedList();
//load array of string objects into linked list
aList = sQ.methodOne(days);
//display linked list as a stack
sQ.methodTwo(aLits);
the method.
//display a linked list as a stack
public LinkedList methodTwo(aList){
for(int i = aList.size; i <= 0; i--)
{
System.out.println(aList.get(i));
}
}//end method two

Your call to the method is correct. The method itself is the problem. You need to specify the type of object being passed into your method.
public LinkedList<String> methodTwo(LinkedList<String> aList){
...
}
You also need to specify the type of your LinkedList in angled brackets, as shown above. That includes when you create your list before passing it around.
LinkedList<String> aList = new LinkedList<>();
The second pair of angled brackets can be empty, as shown above. This is a shortcut introduced in Java 7.

that would be correct. in java, objects are passed by reference (except for primitive types) so you will be able to perform all of the operations on the list you pass to methodTwo.
Please refer to this post for an explanation
Is Java "pass-by-reference" or "pass-by-value"?
Having said that, you do not have any types associated with your List objects, so you will need to specify that.
so something like
public void methodTwo(LinkedList<String> aList){
for(int i = aList.size; i <= 0; i--)
{
System.out.println(aList.get(i));
}
}//end
i have the return type as void, as that is all thats needed if you only need methodTwo for display purpose
and you will also need to declare as
LinkedList<String> aList = new ArrayList<String>();

Related

Java - How to replace entire 2D ArrayList with another that has different size

I have 2D ArrayList consisting of Objects, i pass it to a function in another class, like this:
public void function(ArrayList<ArrayList<Object>>)..
class.function(array)...
then inside of this function i create another 2D ArrayList (with Object type), but this one has different size and amount of values and values themself are different.
How to "assign" this new ArrayList to the one i passed in to a function, so that the passed one becomes exactly like that new one created in a function? And remains the same outside the function of course.
Btw im doing this inside of a function:
ArrayList<ArrayList<Object>> ArrayNew = new ArrayList<ArrayList<Object>>();
for(int i=0; i < y; i++) {
ArrayList<Object> temp = new ArrayList<Object>();
ArrayNew.add(temp);
}
and then i'm adding new values in some way like this:
ArrayNew.get(some_value_that_changes_and_is_lower_than_y).add(tempObject);
Effect identical to
Array = ArrayNew
In Java, you can't reassign a method parameter and have it also reassign the caller's reference. That is just not possible in Java. You either have to modify the passed-in list or return the new list (which you would assign to the variable you want to replace).
Modify passed-in list:
// function(list);
public void function(List<List<Object>> list) {
int y = list.size();
list.clear();
for (int i = 0; i < y; i++) {
list.add(new ArrayList<>());
}
}
Return the new list:
// list = function(list);
public List<List<Object>> function(List<List<Object>> list) {
List<List<Object>> newList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
newList.add(new ArrayList<>());
}
return newList;
}
I don't really know what you're trying to do with the list, so I just made something up close to what your example code does.
Couple notes:
You should use standard Java naming conventions, at least when posting to a public forum such as Stack Overflow. Variable names use camelCase (first letter lowercase). Class/interface names use CamelCase (first letter uppercase).
Unless you need something specific to an implementation, typically you want to declare the types of parameters/variables as the interface (List instead of ArrayList, in this case).
You don't need to declare the generic type arguments on both sides of the = operator, at least not since Java 7.
Assuming your current code looks something like this:
public void foo(ArrayList<ArrayList<Object>> array) {
ArrayList<ArrayList<Object>> newArray = new ArrayList<>();
/* fill newArray with data */
array = newArray; // this will have no effect outside this method
}
public void main() {
ArrayList<ArrayList<Object>> mainArray; /* your outer 2D arrayList */
foo(mainArray);
}
To understand why foo does not change the mainArray object, you can think of calling a method as simply copying its code to your method. Like this:
public void main() {
ArrayList<ArrayList<Object>> mainArray; /* your outer 2D arrayList */
// foo(mainArray); gets replaced with
ArrayList<ArrayList<Object>> array = mainArray;
ArrayList<ArrayList<Object>> newArray = new ArrayList<>();
/* fill newArray with data */
array = newArray;
}
Unsurprisingly, the mainArray remains unchanged, and array refers the same instance as newArray.
As Slaw pointed out, you can either edit the instance mainArray refers to, or make mainArray refer to the new instance instead.
But I would suggest first asking yourself: why do want to edit mainArray in the first place?
It sounds like there might be multiple places in your code referencing mainArray, in which case you should consider refactoring your code.
You should also check that you don't have any references to the inner lists of your mainArray, as those will not reflect the changes you make to the outer list.

Convert generic arraylist to non-generic using Java 8 Stream

I have some old code I'm trying to streamline:
ArrayList arr = (generic arraylist)
int[] newArr = new int[arr.size()];
for(int i=0; i<arr.size(); i++){
newArr[i]=(int)arr.get(i);
}
I want to use the Java Stream API to simplify this. Here is my attempt:
ArrayList arr = (generic arraylist)
List<Integer> = arr.stream().map(m -> (int)m).collect(Collectors.toList());
My understanding is that it would iterate through arr, typecast every object m to an int, and then collect it into a List. But my compiler says that the right-hand-side of the second line returns and Object and not a List. Where am I going wrong?
Per your attempt, it looks like you want to map your ArrayList to an ArrayList<Integer>. The good news is, you don't need to do any of this. The runtime type of ArrayList<Integer> is just ArrayList (this is called type erasure if you want to search for information about it). Only the compiler knows about the parameterized type.
So this code does what you want:
import java.util.ArrayList;
public class Cast {
public static void main(String[] args) {
// This represents the ArrayList of Integer in your existing code
ArrayList raw = new ArrayList(java.util.Arrays.asList(
Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)
));
// You know what it is, so all you need to do is cast
ArrayList<Integer> typed = (ArrayList<Integer>)raw;
// Still works; now recognized as list of integer
for (Integer x : typed) {
System.err.println(x);
}
}
}

ArrayList[] needs unchecked conversion to conform to ArrayList<String>[] [duplicate]

I am trying do something like this:-
public static ArrayList<myObject>[] a = new ArrayList<myObject>[2];
myObject is a class. I am getting this error:- Generic array creation (arrow is pointing to new.)
You can't have arrays of generic classes. Java simply doesn't support it.
You should consider using a collection instead of an array. For instance,
public static ArrayList<List<MyObject>> a = new ArrayList<List<MyObject>();
Another "workaround" is to create an auxilliary class like this
class MyObjectArrayList extends ArrayList<MyObject> { }
and then create an array of MyObjectArrayList.
Here is a good article on why this is not allowed in the language. The article gives the following example of what could happen if it was allowed:
List<String>[] lsa = new List<String>[10]; // illegal
Object[] oa = lsa; // OK because List<String> is a subtype of Object
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
oa[0] = li;
String s = lsa[0].get(0);
There is a easier way to create generic arrays than using List.
First, let
public static ArrayList<myObject>[] a = new ArrayList[2];
Then initialize
for(int i = 0; i < a.length; i++) {
a[i] = new ArrayList<myObject>();
}
You can do
public static ArrayList<myObject>[] a = (ArrayList<myObject>[])new ArrayList<?>[2];
or
public static ArrayList<myObject>[] a = (ArrayList<myObject>[])new ArrayList[2];
(The former is probably better.) Both will cause unchecked warnings, which you can pretty much ignore or suppress by using: #SuppressWarnings("unchecked")
if you are trying to declare an arraylist of your generic class you can try:
public static ArrayList<MyObject> a = new ArrayList<MyObject>();
this will give you an arraylist of myobject (size 10), or if u only need an arraylist of size 2 you can do:
public static ArrayList<MyObject> a = new ArrayList<MyObject>(2);
or you may be trying to make an arraylist of arraylists:
public static ArrayList<ArrayList<MyObject>> a = new ArrayList<ArrayList<MyObject>>();
although im not sure if the last this i said is correct...
It seems to me that you use the wrong type of parenthesis. The reason why you can't define an array of generic is type erasure.
Plus, declaration of you variable "a" is fragile, it should look this way:
List<myObject>[] a;
Do not use a concrete class when you can use an interface.

How to access fields from an array of arrays in Java

import java.util.*;
class Cube{
int width;
int height;
public Cube(int width, int height){
this.width = width;
this.height = height;
}
public String toString(){
String s = "[" + width + "," + height + "]";
return s;
}
}
class myClass {
public static void main(String[] args) {
LinkedList<Cube>[] myCubes;
myCubes = new LinkedList[3];
myCubes[0] = new LinkedList<Cube>();
myCubes[1] = new LinkedList<Cube>();
myCubes[2] = new LinkedList<Cube>();
myCubes[0].add(new Cube(5,2));
myCubes[0].add(new Cube(3,6));
myCubes[1].add(new Cube(3,3));
myCubes[1].add(new Cube(2,2));
myCubes[2].add(new Cube(1,2));
myCubes[2].add(new Cube(5,9));
}
}
I understand that I have an array of arrays. However, I can't quite figure out how to access a single value from a Cube instance in the array.
I would appreciate it if you could help show how to access a single field.
For example, how could I individually access the value 6
myCubes[0].add(new Cube(3,6));
I know that with single instances, you use the dot operator such as
myCubes.width;
myCubes.height;
However, I have no idea how to do access single fields from an array of array of instances.
I would truly appreciate your help.
Thank you
As the others showed you already in the comments.
I tried it out by myself.
If it would be an array of arrays you could simply use
myCubes[0][1].height
But as the LinkedList is not an Array but an Linked List you need to use the get method of linked list to get your element from the list.
System.out.print(myCubes[0].get(1).height);
LinkedList<Cube>[] myCubes ... I understand that I have an array of arrays
No, this not array of arrays, this is array of LinkedList. To
access list you need myCubes[index]
but to access elements from list you need *someList*.get(index).
If we combine those two we get something like myCubes[0].get(1) (just like you did with myCubes[0].add(new Cube(3,6)); where you needed to use add method on a list to put Cube in it).
But generally we should avoid generic types and arrays. Arrays would like to guarantee that they hold only valid values, so they are checking at runtime type of elements which are placed in it to see if they match type of array. For instance while this code will compile:
String[] strArray = new String[10];
Object[] objArr = strArray;
objArr[0] = new Integer(1);
we will get at runtime ArrayStoreException because we attempted to place Integer into array which was supposed to hold only Strings (even if we did it via Object[] reference, type of array is still String[] because that is what we decided on at new String[size]).
But problem with generics is that they are erased at runtime. Because of that it is possible to have code like
List<String> strList = new ArrayList<>();
Object o = strList;
List<Integer> intList = (List<Integer>) o;
intList.add(1);
System.out.println(strList);//this prints [1] !!!
So as you see generic types aren't really that safe (its safety exists mainly at compilation time) so arrays don't like them because they reduce their safety.
So instead of arrays you should use another List like List<List<Cube>>. This way compiler will not complain about mixing arrays and generic types (because there will be no more arrays - at least in our code). Your code using lists can look like:
List<List<Cube>> myCubes = new ArrayList<>();
myCubes.add(new LinkedList<>());
myCubes.add(new LinkedList<>());
myCubes.add(new LinkedList<>());
myCubes.get(0).add(new Cube(5,2));
myCubes.get(0).add(new Cube(3,6));
myCubes.get(1).add(new Cube(3,3));
myCubes.get(1).add(new Cube(2,2));
myCubes.get(2).add(new Cube(1,2));
myCubes.get(2).add(new Cube(5,9));
System.out.println(myCubes.get(0).get(1).width);
System.out.println(myCubes.get(0).get(1).height);
System.out.println(myCubes.get(0).get(1));

array of pair, ArrayList in java

how can I make array of ArrayList or Pair Class which I made myself at the code below.
ex1)
import java.util.*;
class Pair{
static int first;
static int second;
}
public class Main{
public static void main(String[] args){
Vector<Pair>[] v = new Vector<Pair>[100](); //this gives me an error
}
}
1.why the code above gives me an error?
2.my goal is to make an array of vector so that each index of vector holds one or more Pair classes. How can I make it?
another example) : array of ArrayList
import java.util.*;
public class Main{
public static void main(String[] args){
ArrayList<Integer> arr = ArrayList<Integer>(); //I know this line doesn't give error
ArrayList<Integer>[] arr = ArrayList<integer>[500]; // this gives me an error
}
}
3.why does the code above give me an error?
4.my goal is to make an array of ArrayList so that each index of Array has ArrayList/Queue/Vector/Deque whatever. How can I make it?
How about a full generic solution:
ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
The syntax you have used is not what Java uses. If you want to have an array of ArrayLists then do:
ArrayList[] arr = new ArrayList[100];
for(int i=0; i<arr.length; i++)
{
arr[i] = new ArrayList<Pair>(); // add ArrayLists to array
}
Here the type argument <Pair> specifies that the ArrayList should contain items of type Pair. But you can specify any type you wish to use. The same goes for ArrayList, you could replace ArrayList with Vector in the example.
It would be best to use an ArrayList instead of an array in the example. Its much easier to maintain without worrying about the changing length and indexes.
Hope this helps.
public static void main(String[] args){
Vector[] v = new Vector[5];
for(int i=0;i<5;++i){
v[i]= new Vector<Pair>();
}
}
I don't know java that well, but don't you want to do:
ArrayList<ArrayList<Pair>> v = new ArrayList<ArrayList<Pair>>();
Try to break down what containers you need in your question. Your goal is to make a ArrayList (ok, the outer ArrayList satisfies that purpose) that has one or more pair classes in that. "That has" means that "each item in the ArrayList is this type". What would we use to store one or more Pair classes? Another Vector/List of tyoe Pair. So each item in the outer ArrayList is another ArrayList of Pairs.
Note: I moved everything to ArrayList because I read that Vector is somewhat deprecated and they serve similar functions. You may want to check on this.
This example should help with with the next part of your question, but let me know if it doesn't,

Categories