I want to add a trail to a player on a grid, similar to that of the game "Snake." However, when I go to make an array list, I get an error. Here is the code for creating it.
ArrayList<Integer, Integer> trail = new ArrayList<Integer, Integer>();
I get the error "Incorrect number of arguments."
How am I supposed to make this to keep track of which coordinates have been gone over by the player?
Make a class Pair which will look like something like this:
class Pair {
public int x, y;
}
or you can use predefined java.awt.Point class. Then in your code use
ArrayList<Pair>
instead of
ArrayList<Integer, Integer>.
Array list only takes one arguement.
You can refer to this link here.
Solution to your problem is you can use hash map or double dimension array as per your requirement.
ArrayList takes only one argument, like this:
ArrayList<Integer> trail = new ArrayList<Integer>();
If you need to store a key and a value, use HashMap
HashMap<Integer, Integer> trail = new HashMap<Integer, Integer>();
You can also make a Arraylist of integer array like
new Arraylist;
Related
Okay, so I'm fairly new to programming so apologies if this problem is really simple, I've created an ArrayList inside my Hash Map so that I can add more than one value into my hash map.
My code looks fine (to me) but theres an error on this line "mymap.add(module, new ArrayList>());" saying ( or [ expected.
Wasted way too much time trying to figure this out so thought I'd post here. Thanks in advance for any help. Also: yes I need to do it this way and no I can't use guava MultiMap.
public class hashArray {
HashMap<String, ArrayList<Integer>> mymap = new HashMap<String, ArrayList<Integer>>();
public hashArray() {}
public void addEntryHR( String module, Integer result ) {
mymap.add(module, new ArrayList<Integer>>());
There is a typo and a bug in your line:
// The typo is right here v
mymap.add(mod, new ArrayList<Integer>>());
Remove one of the > and change add to put:
mymap.put(mod, new ArrayList<Integer>());
The error you get, is about the typo. Fixing that typo will give you an error about add to be an unknown method.
You need to first get the list out from map object like below-
ArrayList<Integer> list = mymap.get(mod);
if (list==null){
//then create new ArrayList object and assign to list
list=new ArrayList<Integer>();
}
list.add(number); //adding new number to the list
mymap.put(mod,list); //storing in map
The problems
You create a new ArrayList in new ArrayList<Integer>>() (with contains a syntax error as well - a > too many), but never add number to it.
You are calling add on a HashMap, which doesn't have this method. For maps, it is called put.
Proposed solution
Please see the code below
Map<String, List<Integer>> myMap = new HashMap<>();
public void addEntryHR(String mod, Integer number) {
List<Integer> numbers = new ArrayList<>();
numbers.add(number);
myMap.put(mod, numbers);
}
Other remarks
Use interfaces
It is advised to use the interfaces of the collections rather than the implementations. This means Map<String, String> myMap instead of HashMap<String, String> myMap and List<Integer> instead of ArrayList<Integer>.
Why do this? Because this allows you to be flexible in the collections you use and reduce maintenance effort. Say you change your mind and want to use LinkedList instead of ArrayList, then you just have to change one new ArrayList<>() to new LinkedList<>() instead of all the ArrayList variables used throughout the code.
I need to create a list with values of type - (long,String)
like -
ArrayList a = new ArrayList();
a.add(1L,branchName);
How can I do this because if I use list It will accept only int,String.
You should note that ArrayList's add(int,String) adds the String element in the given int index (if the index is valid). The int parameter is not part of the contents of the ArrayList.
Perhaps an ArrayList is not the correct choice for you. If you wish to map Long keys to String values, use Map<Long,String>.
Map<Long,String> a = new HashMap<> ();
a.put(1L,branchName);
You can define a custom class, e.g.
class IndexAndBranchName {
long index;
String branchName;
}
and then add instances of this to the ArrayList:
ArrayList<IndexAndBranchName> a = new ArrayList<>();
a.add(new IndexAndBranchName(index, branchName));
Whether you use this approach or something like Eran's depends upon what you need to use the list for subsequently:
If you want to look "branches" up by index, use a Map; however, you can only store a single value per key; you could use a Guava Multimap or similar if you want multiple values per key.
If you simply want all of the index/branch name pairs, you can use this approach.
You can use the below code for your question.
HashMap is also a better option , but if you want only ArrayList then use it.
List<Map<Object, Object>> mylist = new ArrayList<Map<Object, Object>>();
Map map = new HashMap<>();
map.put(1L, "BranchName");
mylist.add(map);
Alright, so I've been working with PHP for most of my career and find myself needing to use Java. In my case, the biggest issue I have is creating and manipulating arrays in Java.
Example in PHP:
$cars = array(1 => array("stats"=> array("velocity"=>100,
"acceleration"=>0,
"energy"=>30000,
"distance"=>200
)
),
2 => array("stats"=> array("velocity"=>3,
"acceleration"=>6,
"energy"=>30000,
"distance"=>200)
)
);
I'm trying to re-create this type of array in Java but I'm having trouble with initializing it. Is the array considered a String in this case? And must the size of the array be set prior to creating it? e.g: String[][][] car = new String[][][]?
Exactly as aet said in a comment - if you're considering doing this in java - don't. You're doing it wrong.
You should have a class for Car
public class Car {
private int velocity;
private int acceleration;
private int energy;
private int distance;
//getters and setters, a constructor that gets all the property values ...
}
and then store your cars in some collection. An ArrayList is the easiest way:
List<Car> cars = new ArrayList<Car>();
cars.add(new Car(100,0,30000,200));
cars.add(new Car(3,6,30000,200));
Accessing the list of cars would then look like this:
cars.get(0).getVelocity(); //collection indexes start at 0
I think Java doesn't have TRUE multidimensional arrays. An array which is accessed like a[i][j][k] is simply an array, of arrays, of arrays.
You can try the following construct:
String[][] car = new String [][] { { "X0", "Y0"},
{ "X1", "Y1"},
{ "X2", "Y2"},
{ "X3", "Y3"},
{ "X4", "Y4"} };
1) is that "stats" index nesserly? if not, you can:
Map<String, Integer>[] cars = new HashMap<String, Integer>[your length here];
this will index your cars by numbers, skip the "stats" index, and allow you to index the last integer by string:
int velocityOfSecondCar = cars[1].get("velocity"); //note indexing from 0
2) if "stats" index is nesserly, you would have to go one dimension deeper
What you have in PHP there would typically be represented as nested Map instances in Java. For example:
HashMap<Integer,Map<String,Map<String,Integer>>> data = new HashMap<>();
Then you could get values (assuming all levels of the Hash are populated correctly) by saying:
int velocity = data.get(1).get("stats").get("velocity");
Populating nested maps like this can be complicated, and you would typically use a helper method to make sure all the 'parent' levels are populated before you add a data member.
Yes, lenghts must be provided when initializing an array. Hence, your array would look something like this:
int lenght1=x;
int length2=y;
int lenght3=z;
String[][][] car = new String[lenght1][lenght2][lenght3]
I'm no PHP developer myself, but Classes within the array will obey the OOP rules Java implements in terms of abstraction and inheritance. So when you retrieve the elements you can use their corresponding interfaces whatever the class or interface that contains them are.
On the other hand, if you can't know the array lenghts before the initialization you can use class ArrayList, which is almost like a Vector. This class modify its internal length if new elements are added. Along with ArrayList you have a complete set of data structures in the Java specs to store the elements, like Maps, Sets, Lists, etc...
When instantiating an ArrayList you should specify which class or interface will describe the objects you are storing within the data structure, so you'll have to use generics to instantiate the structure. In your case:
ArrayList<String> dim1=new ArrayList<String>();
ArrayList<ArrayList<String>> dim2=new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<ArrayList<String>>> dim3= new ArrayList<ArrayList<ArrayList<String>>>();
As you can see this structure is way sexier than the simple arrays above, but obviusly will require more care to deal with it. Don't forget to instantiate your arraylists before putting them in your 3d matrix, or you'll get an exception later for accesing a null objects.
try this..
Map<Integer, HashMap<String, HashMap<String, Integer>>> map = new HashMap<>();
HashMap<String, Integer> hm = new HashMap<>();
hm.put("Velocity", 1);
hm.put("acceleration", 2);
HashMap<String, HashMap<String, Integer>> state1 = new HashMap<>();
state1.put("state1", hm);
map.put(1, state1);
System.out.println(map);
Hello I would like to implement a Hash map that maps a specific Date to an array of ints. the size of the array is 32
I tried this and it compiles :
HashMap<Date,int[]> coord_map = new HashMap<Date, int[]>();
but I am not sure how this works since I did not give a size for the array of integers.
also I tired this:
int[] arr = new int[32];
for(int i =0; i <32; i++){
arr[i] = 0; // initialize the array to 0.
}
HashMap<Date, arr> attraction_date = new HashMap<Date, arr>();
this gives me a compiler error "Cannot find a class or type named arr"
thank you
I now have a followup question:
I am successfully using one hash map that takes in a date and maps it to an int array.
now I want to use multiple instances of this hashmap. since my project deals with theme park data, there will be one hashmap for every attraction.
so how would I implement an array list of hash maps. To keep track of 20 attractions?
If anyone can show me a sample setup code, that initializes everything, that would be helpful.
thank you again,
It depends on what you do. If the problem requires that you have an array of exactly 32 ints then create a wrapper class IntArray32 and use HashMap<Date, IntArray32>. Otherwise what you have written will work, it will simply allow you to have int array of any size as value.
What you have on top is good, you don't need to specify a size.
This will work
Map<Date, int[]> coordMap = new HashMap<Date, int[]>();
coordMap.put(aDate, new int[]{1,2});
coordMap.put(anotherDate, new int[]{3,4,5,6});
...
So each value int[] can have a different size.
I'm working on a sparse matrix class that needs to use an array of LinkedList to store the values of a matrix. Each element of the array (i.e. each LinkedList) represents a row of the matrix. And, each element in the LinkedList array represents a column and the stored value.
In my class, I have a declaration of the array as:
private LinkedList<IntegerNode>[] myMatrix;
And, in my constructor for the SparseMatrix, I try to define:
myMatrix = new LinkedList<IntegerNode>[numRows];
The error I end up getting is
Cannot create a generic array of LinkedList<IntegerNode>.
So, I have two issues with this:
What am I doing wrong, and
Why is the type acceptable in the declaration for the array if it can't be created?
IntegerNode is a class that I have created. And, all of my class files are packaged together.
For some reason you have to cast the type and make the declaration like this:
myMatrix = (LinkedList<IntegerNode>[]) new LinkedList<?>[numRows];
You can't use generic array creation. It's a flaw/ feature of java generics.
The ways without warnings are:
Using List of Lists instead of Array of Lists:
List< List<IntegerNode>> nodeLists = new LinkedList< List< IntegerNode >>();
Declaring the special class for Array of Lists:
class IntegerNodeList {
private final List< IntegerNode > nodes;
}
Aside from the syntax issues, it seems strange to me to use an array and a linked list to represent a matrix. To be able to access arbitrary cells of the matrix, you would probably want an actual array or at least an ArrayList to hold the rows, as LinkedList must traverse the whole list from the first element to any particular element, an O(n) operation, as opposed to the much quicker O(1) with ArrayList or an actual array.
Since you mentioned this matrix is sparse, though, perhaps a better way to store the data is as a map of maps, where a key in the first map represents a row index, and its value is a row map whose keys are a column index, with the value being your IntegerNode class. Thus:
private Map<Integer, Map<Integer, IntegerNode>> myMatrix = new HashMap<Integer, Map<Integer, IntegerNode>>();
// access a matrix cell:
int rowIdx = 100;
int colIdx = 30;
Map<Integer, IntegerNode> row = myMatrix.get(rowIdx); // if null, create and add to matrix
IntegerNode node = row.get(colIdx); // possibly null
If you need to be able to traverse the matrix row by row, you can make the row map type a TreeMap, and same for traversing the columns in index order, but if you don't need those cases, HashMap is quicker than TreeMap. Helper methods to get and set an arbitrary cell, handling unset null values, would be useful, of course.
class IntegerNodeList extends LinkedList<IntegerNode> {}
IntegerNodeList[] myMatrix = new IntegerNodeList[numRows];
myMatrix = (LinkedList<IntegerNode>[]) new LinkedList[numRows];
casting this way works but still leaves you with a nasty warning:
"Type safety: The expression of type List[] needs unchecked conversion.."
Declaring a special class for Array of Lists:
class IntegerNodeList { private final List< IntegerNode > nodes; }
is a clever idea to avoid the warning. maybe a little bit nicer is to use an interface for it:
public interface IntegerNodeList extends List<IntegerNode> {}
then
List<IntegerNode>[] myMatrix = new IntegerNodeList[numRows];
compiles without warnings.
doesn't look too bad, does it?
List<String>[] lst = new List[2];
lst[0] = new LinkedList<String>();
lst[1] = new LinkedList<String>();
No any warnings. NetBeans 6.9.1, jdk1.6.0_24
There is no generic array creation in Java 1.5 (or 1.6 as far as I can tell). See https://community.oracle.com/message/4829402.
If I do the following I get the error message in question
LinkedList<Node>[] matrix = new LinkedList<Node>[5];
But if I just remove the list type in the declaration it seems to have the desired functionality.
LinkedList<Node>[] matrix = new LinkedList[5];
Are these two declarations drastically different in a way of which I'm not aware?
EDIT
Ah, I think I've run into this issue now.
Iterating over the matrix and initializing the lists in a for-loop seems to work. Though it's not as ideal as some of the other solutions offered up.
for(int i=0; i < matrix.length; i++){
matrix[i] = new LinkedList<>();
}
You need an array of List, one alternative is to try:
private IntegerNode[] node_array = new IntegerNode[sizeOfYourChoice];
Then node_array[i] stores the head(first) node of a ArrayList<IntegerNode> or LinkedList<IntegerNode> (whatever your favourite list implementation).
Under this design, you lose the random access method list.get(index), but then you could still traverse the list starting with the head/fist node store in the type safe array.
This might be an acceptable design choice depending on your use case. For instance, I use this design to represent an adjacency list of graph, in most use cases, it requires traversing the adjacency list anyway for a given vertex instead of random access some vertex in the list.