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.
Related
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?
I got this line of code when I asked the teacher for some help, but I get a redline below the last part. What could be wrong? The error message: "The type of the expression must be an array type but it resolved to ArrayList" I don't understand that, please help me to understand.
ArrayList<Point>[] touchPoints = new ArrayList<Point>()[2];
I want to have two lists to save Points. I guess I call each list like touchPoints[0]; and touchPoints[1]; !?
EDIT:
I guess I can keep it simple and just use two different List like this!?:
points1 = new ArrayList<Point>();
points2 = new ArrayList<Point>();
You have created an array of ArrayLists. This demo shows how they are used together
import java.util.ArrayList;
public class ArraysAndLists {
public static void main(String[] args) {
ArrayList<String>[] touchPoints = new ArrayList[2];
// Adding values
touchPoints[0] = new ArrayList<String>();
touchPoints[0].add("one string in the first ArrayList");
touchPoints[0].add("another string in the first ArrayList");
touchPoints[1] = new ArrayList<String>();
touchPoints[1].add("one string in the second ArrayList");
touchPoints[1].add("another string in the second ArrayList");
// touchPoints[2].add("This will give out of bounds, the array only holds two lists");
// Reading values
System.out.println(touchPoints[0].get(0)); // returns "one string in the first ArrayList"
System.out.println(touchPoints[1].get(1)); // returns "another string in the second ArrayList"
}
}
check out this Question
The component type of an array object may not be a type variable or a parameterized type, unless it is an (unbounded) wildcard type.You can declare array types whose element type is a type variable or a parameterized type, but not array objects.
You are mixing two things:
Constructing a plain array
Constructing an ArrayList
Constructing an array
A plain array is very low level. Does not have methods, and its length is fixed after you create it.
MyType[] anArray = new MyType[10];
Constructing an ArrayList
ArrayList is just an implementation of a type of Collection
Collection<MyItemType> aCollection = new ArrayList<MyItemType>();
What to do in your case?
You want a plain array of collections (which implementation is ArrayList). So:
// Create the array, use the interface in case you need to change the implementation later on
Collection<Point>[] touchPoints = (Collection<Point>) new Collection[2];
// Create each collection within that array, using the ArrayList implementation
touchPoints[0] = new ArrayList<Point>();
touchPoints[1] = new ArrayList<Point>();
How to do it better?
Try to think about why you need a plain array:
if it's just 2 elements, and always fixed, simply create two member variables.
if number can vary, just create a Collection of Collections (Collection>)
Edit given your use case:
Just create a class to hold your user input:
class UserInput {
public UserInput() {
user1TouchPoints = new ArrayList<Point>();
user2TouchPoints = new ArrayList<Point>();
}
// Add accessors and all
private Collection<Point> user1TouchPoints;
private Collection<Point> user2TouchPoints;
}
If you plan to have more players, simply use a map
class UserInput {
public UserInput() {
usersTouchPoints = new HashMap<Integer, Collection<Point>>();
}
public Collection<Point> getUserTouchPoints(Integer userId) {
return usersTouchPoints.get(userId);
}
public void addUserTouchPoints(Integer userId, Collection<Point> input) {
Collection<Point> points = usersTouchPoints.get(userId);
if (points==null) {
points = new ArrayList<Point>();
userTouchPoints.put(userId, points);
}
points.addAll(input);
}
// Maps a user ID (or index) to its touch points
// If you are using Android, use SparseArray instead of Map, this is more efficient
private Map<Integer, Collection<Point>> usersTouchPoints;
}
So a part of my homework is to get a string of integer numbers and put each one of them in a list, this is what I have done:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String N;
int count;
LinkedList<Integer> booksList = new LinkedList<>();
System.out.printf("Give: ");
N = input.nextLine();
String[] arr = N.split(" ");
for (count = 0; count < arr.length - 2; count++) {
booksList.add(Integer.parseInt(arr[count + 2]));
}
So what I've done is take the string, split it into an array and then take the items with the for loop and put them into a list. What I am confused with is that I see people using the add command with a "new" inside the parentheses like this:
booksList.add(new Integer.parseInt(arr[count + 2]));
This is confusing me and I'm not totally sure if I'm doing this the right way.
By the way, I take the array elements from count + 2 because I do not need the first two elements of the answer but I need to store the first two integers in two separate variables.
Also I've seen some people write this:
List<Integer> booksList = new LinkedList<>();
Is there any difference from that and what I've written?
The construct
List<Integer> booksList = new LinkedList<>();
is often seen for mainly 2 reasons:
a) You aren't sure what the best collection for your purpose is. There are many candidates: Arrays, Sets, Lists, Vector, Map and so on, but you have to use something specific. So on the right hand side it has to be concrete, but on the left hand side, you try to be as wide open as possible.
Very often you just do iterate over the collection, use a for loop, search, sort, put into, take from, delete.
If you find out, that a sibling of your first thought is better suited, you can later change the RHS, without need to rewrite the rest of your program, because, for example, most methods of LinkedList and ArrayList fullfill the same contract, defined in List.
b) You get mor compatible to the outside world, if you use the wider object. Of course, you can't use something as vague as Object, since Object has no .add (E) Method.
But for sorting, searching and so on List is well suited. Have a look at the documentation, and compare List, LinkedList and ArrayList. Try to replace the one with another in your code.
Maybe two 'sublist (int fromIndex, int toIndex)' methods, in Linked~ and ArrayList are defined in the base class, and behave identically.
But maybe they are specialized, and implement subList on their own. Here we have a Interface <- Class relationship, so we know, that there is no implementation in the Interface, it is completly abstract. But in the case of (Abstract) base classes <- derived classes the pattern is the same.
Derived/implementing classes share the same interface, 'public List sublist (int fromIndex, int toIndex)'. You expect them to produce the same result, but in different ways - maybe.
Only if you need to call a method which is only present in, say LinkedList, you either declare your bookList as LinkedList up front, or you cast it for that purpose:
List<Integer> books = new LinkedList<>();
// ...
LinkedList <Integer> booksLiLi = (LinkedList <Integer>) books <> ();
// do something with booksLiLi which isn't defined on the List interface.
Sidenote: Your code can be simplified with the modern (7 years old) foreach-loop:
Scanner input = new Scanner (System.in);
LinkedList<Integer> booksList = new LinkedList<>();
System.out.printf ("Give: ");
String N = input.nextLine ();
String[] arr = answer.split (" ");
for (String num: arr) {
booksList.add (Integer.parseInt (num));
}
bookList.remove ();
bookList.remove ();
But if you declare a Scanner, you can take Integers from the Scanner directly:
Scanner input = new Scanner (System.in);
LinkedList<Integer> booksList = new LinkedList<>();
System.out.printf ("Give: ");
while (input.hasNextInt ()) {
booksList.add (input.nextInt ());
}
bookList.remove ();
bookList.remove ();
In reaction to the comments, here is a third code: Reading from System.in a line, and then creating a Scanner on that that line:
String line = input.nextLine ();
Scanner valueLine = new Scanner (line);
List<Integer> books = new LinkedList<>();
while (valueLine.hasNextInt ()) {
books.add (valueLine.nextInt ());
}
The function Integer.parseInt returns a new Integer so you do not need to use the new keyword.
Keep experimenting and use an IDE such as Eclipse that will highlight compile errors and you will learn the language soon enough. If you still are struggling read online tutorials or ask your professor.
Your code is fine.
The following:
booksList.add(new Integer.parseInt(arr[count + 2]));
is not syntactically correct, whereas what you have is.
As to List<Integer> booksList = ... vs LinkedList<Integer> booksList = ..., I consider the former to be slightly better style. However, it is sometimes necessary to use the latter. The difference is largely stylistic and I wouldn't worry about it too much right now.
Finally, I'd like to echo what others have said in the comments: declare variables when they're first used and not before. Also, don't reuse variables.
A List in Java is an interface, from which the methods are defined in specific implementations. For example, LinkedList implements the List interface, and creates its own version of add, delete and other methods. This is pretty important, since other data structures, such as ArrayList also implement the List interface. Add, delete, and other methods operate very differently in LinkedList and ArrayList.
When you write
List<Integer> booksList = new LinkedList<>()
it operates the same as
LinkedList<Integer> booksList = new LinkedList<>()
since the new keyword creates a LinkedList object which is bound to the name booksList. booksList just happens to be a List object in the first example, from which LinkedList implements.
Check the docs and see what data structures implement the List interface. You'll be surprised how many ways a List<Integer> newList = new .... is valid code.
One thing that hasn't been mentioned is its a good idea to pass on the generic type in all the angle brackets when declaring a data structure.
ie List<Integer> booksList = new LinkedList<Integer>()
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,
I was wondering what the simplest way would be to implement an array who's rank is specified at runtime.
The example I am working on stores a array of boolean values for lattice points, and I want the user to be able to chose how many spatial dimensions the model uses at runtime.
I've looked at the Array.newInstance() method:
dimensionOfSpace = userInputValue; // this value comes from GUI or whatever
int latticeLength = 5; // square lattice for simplicity
int[] dimensions = new int[dimensionOfSpace];
for(int i = 0; i < l.length; i++) l[i] = length;
Object lattice = Array.newInstance(boolean.class, dimensions);
But accessing these values in any sort of way seems to require horribly slow methods such as recursively using Array.get until the returned value is no longer an array, i.e. using isArray().
Am I missing an obvious solution here? I would love to be able to access the values in a way similar to foo[i][j][k].
Looks like what you are looking for is for some way to declare how many dimensions an array has at runtime. I don't know how this could be done using a multidimensional ArrayList, or any multidimensional structure where you have to specify the dimensionality at compile time.
The only answer I see is to use a simple linear array wrapped in a class that converts multidimensional coordinate to and from the its position in the underlying array. This is basically how languages such as C stores multidimensional arrays by using one contiguous chunk of memory.
The code would look something like this:
import java.util.*;
class MultiArray<T>{
private int[] dimensions;
private Object[] array;
public MultiArray(int ... dimensions){
this.dimensions=dimensions;
//Utils.product returns the product of the ints in an array
array=new Object[Utils.product(dimensions)];
}
public void set(T value, int ... coords){
int pos=computePos(coords);
array[pos]=value;
}
public T get(int ... coords){
int pos=computePos(coords);
return (T)(array[pos]);
}
private int computePos(int[] coords){
int pos=0;
int factor=1;
for (int i=0;i<coords.length;i++){
pos+=factor*coords[i];
factor*=dimensions[i];
}
return pos;
}
}
class Main{
public static void main(String args[]){
MultiArray<Integer> m=new MultiArray<Integer>(new int[]{5,4,3});
Random r=new Random();
for(int i=0;i<5;i++)
for(int j=0;j<4;j++)
for(int k=0;k<3;k++)
m.set(r.nextInt(),i,j,k);
for(int i=0;i<5;i++){
for(int j=0;j<4;j++){
for(int k=0;k<3;k++)
System.out.print(m.get(i,j,k)+" ");
System.out.println("");
}
System.out.println("\n");
}
}
}
class Utils{
public static int product(int...a){
int ret=1;
for (int x:a) ret*=x;
return ret;
}
}
Checkout Java Collections. It contains a class called ArrayList that grows in size as needed.
One dimensional
List<Boolean> a = new ArrayList<Boolean>();
Two Dimensional
List<List<Boolean>> b = new List<List<Boolean>>();
Three Dimensional
List<List<List<Boolean>>> c = new List<List<List<Boolean>>>();
And you'd access the item as c.get(i).get(j).get(k) instead of c[i][j][k] as in a 3d array. Or even better, wrap it in your own Class, and use a get() method there. So it becomes:
c.get(i, j, k);
Edit:
To have a multi-dimensional list of depth N, remove the Boolean type indictor and simply create lists as
List level1 = new ArrayList();
List level2 = new ArrayList();
List level3 = new ArrayList();
level1.add(level2);
level2.add(level3);
and so on..
I'm going to use the term 'rank' to mean the 'number-of-dimensions' in your array. So a vector has rank 1, a matrix has rank 2 and so on. You've already accepted an answer that by your own admission is not quite what you want. Here's an alternative to settling for less:
Recall that computer memory is essentially linear and that what a compiler does when it gives you arrays is actually take care of transforming an index expression into a linear address. This is simplest to think about if you assume that all arrays are in contiguous memory, not always true. Suppose that you make a declaration such as ARRAY_OF_TYPE[10][10][10], ie it has 1000 elements. Then the element at position [3][5][4] is (my arrays are indexed from 1 not 0 -- change the sums that follow if you want to) at location baseAddress+354*size_of_element_of_TYPE.
I expect you know where I'm going on this by now ...
At run time your program prompts for a list of integers from the user. Each integer specifies the size of one of the dimensions of the array, the number of integers specifies the rank of the array. Your program does some multiplications and you allocate a vector of the right length. OK, you have to write the indexing and de-indexing functions, but these should be fairly straightforward.
et voila you have an array whose rank is established at run time.
I did a quick google search for "java tensor" which came up with DJEP, could that be something which fits your bill?