array of pair, ArrayList in java - 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,

Related

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 of 2 Dimensional arrays

I created a very simple program to create an ArrayList of 2 Dimensional arrays of floats.
But adding new elements in the list seems to overwrite or corrupt previous elements.
What am i doing wrong and how should this functionality be implemented?
import java.util.ArrayList;
public class multiDArrayTest {
public static void main(String[] args) {
float[][] coeff = new float[3][6];
ArrayList<float[][]> basisCoeffs;
basisCoeffs = new ArrayList<float [][]>(2);
coeff[0][0] = 0;
coeff[0][1] = 100;
coeff[0][2] = -50;
basisCoeffs.add(coeff);
coeff[0][0] = 50;
coeff[0][1] = 200;
coeff[0][2] = -400;
basisCoeffs.add(coeff);
System.out.println(basisCoeffs.get(0)[0][0]);
System.out.println(basisCoeffs.get(0)[0][1]);
System.out.println(basisCoeffs.get(0)[0][2]);
//I should get 0 100 -50 50, but i don't? Where does it go ??
System.out.println(basisCoeffs.get(1)[0][0]);
System.out.println(basisCoeffs.get(1)[0][1]);
System.out.println(basisCoeffs.get(1)[0][2]);
}
}
Here you add the array to the ArrayList, you modify that array, then you add it to the ArrayList a second time. So you have two copies of the same array in the ArrayList. I think you are confusing primitives and objects here. Arrays are objects, so they can be modified. When you get the elements out of the ArrayList, you see both elements point to that same array, which you modified, so you get the modified values back out. If you don't want that behavior, just clone the array when you add it to the ArrayList. Something like basicCoeffs.add(coeff.clone());.
What happens is that you have the coeff array with the first values, you add it to the list and everything is fine, but when you edit coeff again before adding it to the list, you also edit the one that is in position 0 of the list, since both coeff as the element in position 0 of the list they refer to the same object in Java. One option would be to create a copy and another to have the two arrays separately. Also, since I observe that your dimensions are static, you can directly add the values to the designated positions, for example:
import java.util.ArrayList;
public class multiDArrayTest {
public static void main(String[] args) {
ArrayList<float[][]> basisCoeffs = new ArrayList<float [][]>(2);
basisCoeffs.add(new float[3][6]);
basisCoeffs.add(new float[3][6]);
// First values of coeffs
basisCoeffs.get(0)[0][0] = 0;
basisCoeffs.get(0)[0][1] = 100;
basisCoeffs.get(0)[0][2] = -50;
// Second values of coeffs
basisCoeffs.get(1)[0][0] = 50;
basisCoeffs.get(1)[0][1] = 200;
basisCoeffs.get(1)[0][2] = -400;
System.out.println(basisCoeffs.get(0)[0][0]);
System.out.println(basisCoeffs.get(0)[0][1]);
System.out.println(basisCoeffs.get(0)[0][2]);
System.out.println(basisCoeffs.get(1)[0][0]);
System.out.println(basisCoeffs.get(1)[0][1]);
System.out.println(basisCoeffs.get(1)[0][2]);
}
}
Arrays in java are Mutable and pass by reference (well, pass by value of reference). this means is you change an element in an array, the reference is changed. So what do we have to do to avoid these side effects?
You can encapsulate Lists and arrays and just add a copy of objects into arrays.
if you're using Java 9 or later you can use List<float[][]> basisCoeffs = List.of(coeff) to add its Item as an immutable list.
you can read more about mutables and immutables here: Immutable class?

How to pass a linked list in 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>();

Creating chronological variable names automatically

I am writing a program that will take input of polynomials. Needing to create a new ArrayList for each polynomial input, I am needing a way to name each list without knowing the amount of polynomial beforehand. If a file has 2 polynomials I will need to name 2 arrays, but if more polynomials I will need to name more arrays. Is there anyway to automatically name arrays or variables with the iteration of a loop. I cannot figure out how. Variable names such as : P1 , P2, P3 etc. as the number of Polynomials increases is what I am searching for. Each polynomial will be read in line by line. I have attached my code, Though it is nowhere near complete. I imagine I will need to move the PolyCalc creation into the while loop and create a new PolyCalc for each line of input. I am looking to add this feature to the while loop in the main method.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class PolyProcessor {
static int polyNum = 0;
public static void main(String[] args) throws FileNotFoundException{
File polyfile = new File("polyinput.txt");
Scanner read = new Scanner(polyfile);
while (read.hasNextLine()){
PolyCalc c = new PolyCalc();
String j = read.nextLine();
c.add(j.split(";"));
polyNum++;}
}
}
class PolyCalc{
static int polyCount = 0;
static ArrayList polynomials = new ArrayList();
static void add(String[] strings){
for(int i = 0; i<strings.length;i++){
polynomials.add(strings[i]);
polyCount++;}
}
static Object get(int i){
return polynomials.get(i);
}
}
Why not use a (Hash) Map where the key is the variable name?
Map polys = new HashMap();
int count=0;
For ...
string key = String.format("p%02d",count++);
polys.put(key, newPoly(...));
I'd have to look up the String.format but something like that.
The order needs to be preserved so just choose long enough zero padded keys that you can sort. And/or use a linkedHashMap which keeps the insertion order.
As Stephen's answer and you said that arraylist is mandatory you could still use ArrayList
ArrayList numbers = new ArrayList();
HashMap<String,ArrayList> myPolys = new HashMap<String,ArrayList>();
and to use the HashMap
myPolys.put(what do you want to call them or your so "called" variables , numbers);
First of all, you can't do this using variables. Java does not allow you to declare variables dynamically. It is not that kind of programming language ...
If it is mandatory that the polynomials are stored in an ArrayList then:
get the user to refer to the polynomials by number (i.e. position in the list) instead of by name, or
create a hashmap that maps from names to positions in the list, or
store the polynomials in BOTH an ArrayList<String> AND a HashMap<String, String>.
Actually, I think that you may have misinterpreted the requirements for your programming exercise. I suspect that you are asked to represent each individual polynomial as an ArrayList (or a custom class that has an ArrayList inside it). Representing a polynomial as a String doesn't allow you to do any operations on it ... without first parsing the String and turning it into another form.
As you absolutely need to use ArrayList class to store your polynomials you can use its add(int index, E Element) method as follows:
List polynomials= new ArrayList();
for(int k=0;k < counter;k++){
polynomials.add(k, new Poly(...));
}
You won't have P0, P1, ... but polynomials.get(0), polynomials.get(1), ...
Thanks to gmhk in this.

if i don't know array will be have how many elements?

I want to give an example.
import java.util.Scanner;
public class ana
{
public static void main(String[] args) {
int[] array = new int[9]; // create array that have "9" elements
}
}
Above example's array have 9 elements but i want to create unlimited array.
If I want this when I'm writing PHP I write this code:
<?php
$example = array();
$example[] = 15; // auto numbering. PHP don't want number of array's element.
$example[] = 20;
?>
And what does mean?
Auto[] array = {new Auto()};
I hope I made myself clear.
Use a List (such as an ArrayList). Java has a number of collections (List, Set, Map, Queue, etc.), with various implementations. Learn how to use them by reading the collections tutorial.
You need to use a different data structure, like a Vector.
Try using ArrayList, resizable-array implementation of the List interface in Java.
Use ArrayList in java.
ArrayList<Integer> array = new ArrayList<Integer>();
I think you need an ArrayList:
ArrayList<Integer> as = new ArrayList<Integer>();
as.add(15);
as.add(20);
and Auto[] array = {new Auto()}; is a Array of Type Auto with one element.

Categories