How do you pass Array dimensions? - java

How do you pass Array dimensions along with the Array in java?
I invision something like this:
public String[1][1] abc(){
return theStringArray
}
//but this isn't possible
So is there a way to pass dimensions of arrays?
Right now I have 2 methods that pass an int for each dimension but is there a better way of doing this?
The problem at it's heart is this:
When I try to pass the array and find it's length, it gives me a load of errors. The problem is that the array for the class receiving the array needs to initialize the array the the passed array will copy to, but without the passed arrays dimensions, how can I initialize it?
Class the array is passed to:
String[][] lordStats;
ArrayList<String> troopList;
public void loader() {
lord lorder = new lord();
lordStats = lorder.returnLord();
total = lorder.returnLordTotal();
for (int i = 0; i < lordStats[0].length; i++)
troopList.add (lordStats[i][2]);
}
Class the array comes from: note that method lord creator is called multipul times.
public class lord {
static int total;
String[][] lordStats;
public void total(int total1) {
total = total1;
System.out.println("lordTotal");
}
public void lordCreator(String lord, String kingdom, String troop, int times) {
lordStats = new String[total][3];
System.out.println("animalStats");
lordStats[times][0] = lord;
lordStats[times][1] = kingdom;
lordStats[times][2] = troop;
}
public String[][] returnLord() {
return lordStats;
}

In Java, you usually don't have to pass array dimensions along with the array, since every array implicitly knows its own dimensions.
If the array is called arr, then arr.length would return its size. If arr is a 2D array, then arr[0].length would give the size of the first row; arr[1].length is the size of the next row, and so on.
If the function is to allocate an array of caller-specified size, simply pass the desired dimensions into the function as int arguments.

You don't have to explicitly pass array dimensions in Java, arrays have length properties for that.
public String[][] abc() {
return new String[10][10];
}

You can figure out the length of an array with just .length. But Java arrays are just arrays of arrays (not N-dimensional blocks of contiguous elements).
Thus, they can be jagged, meaning each row has a different number of columns. So you can only rely on the length of theStringArray[0] (the column count for the first row) equaling theStringArray[1] if there is a documented understanding that theStringArray is not jagged.

All arrays in Java are 1-dimensional. You can have an array of arrays, which is effectively a 2-dimensional array. However, each element can have a different length and there is no way to enforce a single second dimension size. You can do something like this:
public String[][] makeArray(int rows, int columns) {
return new String[rows][columns];
}
Then you can query the array as follows:
String[][] array = makeArray(1, 1);
System.out.println("Row count: " + array.length);
System.out.println("Column count: " + array[0].length); // assumes >0 elements
However, someone could do this:
String[][] array = makeArray(3, 3);
array[0] = new String[1];
The previous code would then give a misleading result for the number of columns.

Related

What are the functions of an array of an arrayList?

I tried to do:
static boolean newTrait(ArrayList<Integer> population, int[] traits) {
for(int i = 0; i < 25; i++) {
for(int j = 0; j < 625; j++) {
if(traits[j].equals(population[i].get(i))) {
return false;
}
}
}
return true;
}
The java compiler said that I had an "unresolved compiler issue."
Can anyone help?
[X] operator is for arrays. You don't have an ArrayList array you just have an ArrayList<> which, although it has "Array" in the name, is not an array and so cannot be accessed with [X]. ArrayList is an object with regular methods.
It's perfectly valid to have an ArrayList array
e.g.
static boolean newTrait(ArrayList<Integer>[] population, int[] traits)
where each element in the population array IS A ArrayList. In which case you would first need to access the element in the array (via [X]) and then access the elements IN the ArrayList using get()
e.g. get the first element of the array
ArrayList<Integer> firstList = population[0];
then get the Xth item in the list
e.g.
firstList.get(x);
All simple types (not objects) do not have any methods. In your case neither the array not the int values inside the array have methods.
Fix:
if(traits[j] == population.get(i))
{
return false;
}
This compares an int on the left side with an Integer on the right side. For int the == operator is correct but it would be wrong for Integers. However in this case the compiler does automatically 'unbox' the Integer on the right side to int.
Notice that I removed the wrong [i] after population as well. Population is not an array.

How do I store user-entered names in array to be called in a later method? I can't ask for the number of names before hand, but know max [duplicate]

I have a class - xClass, that I want to load into an array of xClass so I the declaration:
xClass mysclass[] = new xClass[10];
myclass[0] = new xClass();
myclass[9] = new xClass();
However, I don't know if I will need 10. I may need 8 or 12 or any other number for that matter. I won't know until runtime.
Can I change the number of elements in an array on the fly?
If so, how?
No you can't change the size of an array once created. You either have to allocate it bigger than you think you'll need or accept the overhead of having to reallocate it needs to grow in size. When it does you'll have to allocate a new one and copy the data from the old to the new:
int[] oldItems = new int[10];
for (int i = 0; i < 10; i++) {
oldItems[i] = i + 10;
}
int[] newItems = new int[20];
System.arraycopy(oldItems, 0, newItems, 0, 10);
oldItems = newItems;
If you find yourself in this situation, I'd highly recommend using the Java Collections instead. In particular ArrayList essentially wraps an array and takes care of the logic for growing the array as required:
List<XClass> myclass = new ArrayList<XClass>();
myclass.add(new XClass());
myclass.add(new XClass());
Generally an ArrayList is a preferable solution to an array anyway for several reasons. For one thing, arrays are mutable. If you have a class that does this:
class Myclass {
private int[] items;
public int[] getItems() {
return items;
}
}
you've created a problem as a caller can change your private data member, which leads to all sorts of defensive copying. Compare this to the List version:
class Myclass {
private List<Integer> items;
public List<Integer> getItems() {
return Collections.unmodifiableList(items);
}
}
In java array length is fixed.
You can use a List to hold the values and invoke the toArray method if needed
See the following sample:
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
public class A {
public static void main( String [] args ) {
// dynamically hold the instances
List<xClass> list = new ArrayList<xClass>();
// fill it with a random number between 0 and 100
int elements = new Random().nextInt(100);
for( int i = 0 ; i < elements ; i++ ) {
list.add( new xClass() );
}
// convert it to array
xClass [] array = list.toArray( new xClass[ list.size() ] );
System.out.println( "size of array = " + array.length );
}
}
class xClass {}
As others have said, you cannot change the size of an existing Java array.
ArrayList is the closest that standard Java has to a dynamic sized array. However, there are some things about ArrayList (actually the List interface) that are not "array like". For example:
You cannot use [ ... ] to index a list. You have to use the get(int) and set(int, E) methods.
An ArrayList is created with zero elements. You cannot simple create an ArrayList with 20 elements and then call set(15, foo).
You cannot directly change the size of an ArrayList. You do it indirectly using the various add, insert and remove methods.
If you want something more array-like, you will need to design your own API. (Maybe someone could chime in with an existing third party library ... I couldn't find one with 2 minutes "research" using Google :-) )
If you only really need an array that grows as you are initializing it, then the solution is something like this.
ArrayList<T> tmp = new ArrayList<T>();
while (...) {
tmp.add(new T(...));
}
// This creates a new array and copies the element of 'tmp' to it.
T[] array = tmp.toArray(new T[tmp.size()]);
You set the number of elements to anything you want at the time you create it:
xClass[] mysclass = new xClass[n];
Then you can initialize the elements in a loop. I am guessing that this is what you need.
If you need to add or remove elements to the array after you create it, then you would have to use an ArrayList.
You can use ArrayList:
import java.util.ArrayList;
import java.util.Iterator;
...
ArrayList<String> arr = new ArrayList<String>();
arr.add("neo");
arr.add("morpheus");
arr.add("trinity");
Iterator<String> foreach = arr.iterator();
while (foreach.hasNext()) System.out.println(foreach.next());
As other users say, you probably need an implementation of java.util.List.
If, for some reason, you finally need an array, you can do two things:
Use a List and then convert it to an array with myList.toArray()
Use an array of certain size. If you need more or less size, you can modify it with java.util.Arrays methods.
Best solution will depend on your problem ;)
Arrays.copyOf() method has many options to fix the problem with Array length increasing dynamically.
Java API
Yes, wrap it and use the Collections framework.
List l = new ArrayList();
l.add(new xClass());
// do stuff
l.add(new xClass());
Then use List.toArray() when necessary, or just iterate over said List.
I recommend using vectors instead. Very easy to use and has many predefined methods for implementation.
import java.util.*;
Vector<Integer> v=new Vector<Integer>(5,2);
to add an element simply use:
v.addElement(int);
In the (5,2) the first 5 is the initial size of the vector. If you exceed the initial size,the vector will grow by 2 places. If it exceeds again, then it will again increase by 2 places and so on.
Where you declare the myclass[] array as :
xClass myclass[] = new xClass[10]
, simply pass in as an argument the number of XClass elements you'll need. At that point do you know how many you will need? By declaring the array as having 10 elements, you are not declaring 10 XClass objects, you're simply creating an array with 10 elements of type xClass.
Java Array sizes are fixed , You cannot make dynamic Arrays as that of in C++.
Yes, we can do this way.
import java.util.Scanner;
public class Collection_Basic {
private static Scanner sc;
public static void main(String[] args) {
Object[] obj=new Object[4];
sc = new Scanner(System.in);
//Storing element
System.out.println("enter your element");
for(int i=0;i<4;i++){
obj[i]=sc.nextInt();
}
/*
* here, size reaches with its maximum capacity so u can not store more element,
*
* for storing more element we have to create new array Object with required size
*/
Object[] tempObj=new Object[10];
//copying old array to new Array
int oldArraySize=obj.length;
int i=0;
for(;i<oldArraySize;i++){
tempObj[i]=obj[i];
}
/*
* storing new element to the end of new Array objebt
*/
tempObj[i]=90;
//assigning new array Object refeence to the old one
obj=tempObj;
for(int j=0;j<obj.length;j++){
System.out.println("obj["+j+"] -"+obj[j]);
}
}
}
Since ArrayList takes to much memory when I need array of primitive types, I prefer using IntStream.builder() for creating int array (You can also use LongStream and DoubleStream builders).
Example:
Builder builder = IntStream.builder();
int arraySize = new Random().nextInt();
for(int i = 0; i<arraySize; i++ ) {
builder.add(i);
}
int[] array = builder.build().toArray();
Note: available since Java 8.
It is a good practice get the amount you need to store first then initialize the array.
for example, you would ask the user how many data he need to store and then initialize it, or query the component or argument of how many you need to store.
if you want a dynamic array you could use ArrayList() and use al.add(); function to keep adding, then you can transfer it to a fixed array.
//Initialize ArrayList and cast string so ArrayList accepts strings (or anything
ArrayList<string> al = new ArrayList();
//add a certain amount of data
for(int i=0;i<x;i++)
{
al.add("data "+i);
}
//get size of data inside
int size = al.size();
//initialize String array with the size you have
String strArray[] = new String[size];
//insert data from ArrayList to String array
for(int i=0;i<size;i++)
{
strArray[i] = al.get(i);
}
doing so is redundant but just to show you the idea, ArrayList can hold objects unlike other primitive data types and are very easy to manipulate, removing anything from the middle is easy as well, completely dynamic.same with List and Stack
I don't know if you can change the size at runtime but you can allocate the size at runtime. Try using this code:
class MyClass {
void myFunction () {
Scanner s = new Scanner (System.in);
int myArray [];
int x;
System.out.print ("Enter the size of the array: ");
x = s.nextInt();
myArray = new int[x];
}
}
this assigns your array size to be the one entered at run time into x.
Here's a method that doesn't use ArrayList. The user specifies the size and you can add a do-while loop for recursion.
import java.util.Scanner;
public class Dynamic {
public static Scanner value;
public static void main(String[]args){
value=new Scanner(System.in);
System.out.println("Enter the number of tests to calculate average\n");
int limit=value.nextInt();
int index=0;
int [] marks=new int[limit];
float sum,ave;
sum=0;
while(index<limit)
{
int test=index+1;
System.out.println("Enter the marks on test " +test);
marks[index]=value.nextInt();
sum+=marks[index];
index++;
}
ave=sum/limit;
System.out.println("The average is: " + ave);
}
}
In Java Array Sizes are always of Fixed Length But there is way in which you can Dynamically increase the Size of the Array at Runtime Itself
This is the most "used" as well as preferred way to do it-
int temp[]=new int[stck.length+1];
for(int i=0;i<stck.length;i++)temp[i]=stck[i];
stck=temp;
In the above code we are initializing a new temp[] array, and further using a for loop to initialize the contents of the temp with the contents of the original array ie. stck[]. And then again copying it back to the original one, giving us a new array of new SIZE.
No doubt it generates a CPU Overhead due to reinitializing an array using for loop repeatedly. But you can still use and implement it in your code.
For the best practice use "Linked List" instead of Array, if you want the data to be stored dynamically in the memory, of variable length.
Here's a Real-Time Example based on Dynamic Stacks to INCREASE ARRAY SIZE at Run-Time
File-name: DStack.java
public class DStack {
private int stck[];
int tos;
void Init_Stck(int size) {
stck=new int[size];
tos=-1;
}
int Change_Stck(int size){
return stck[size];
}
public void push(int item){
if(tos==stck.length-1){
int temp[]=new int[stck.length+1];
for(int i=0;i<stck.length;i++)temp[i]=stck[i];
stck=temp;
stck[++tos]=item;
}
else
stck[++tos]=item;
}
public int pop(){
if(tos<0){
System.out.println("Stack Underflow");
return 0;
}
else return stck[tos--];
}
public void display(){
for(int x=0;x<stck.length;x++){
System.out.print(stck[x]+" ");
}
System.out.println();
}
}
File-name: Exec.java
(with the main class)
import java.util.*;
public class Exec {
private static Scanner in;
public static void main(String[] args) {
in = new Scanner(System.in);
int option,item,i=1;
DStack obj=new DStack();
obj.Init_Stck(1);
do{
System.out.println();
System.out.println("--MENU--");
System.out.println("1. Push a Value in The Stack");
System.out.println("2. Pop a Value from the Stack");
System.out.println("3. Display Stack");
System.out.println("4. Exit");
option=in.nextInt();
switch(option){
case 1:
System.out.println("Enter the Value to be Pushed");
item=in.nextInt();
obj.push(item);
break;
case 2:
System.out.println("Popped Item: "+obj.pop());
obj.Change_Stck(obj.tos);
break;
case 3:
System.out.println("Displaying...");
obj.display();
break;
case 4:
System.out.println("Exiting...");
i=0;
break;
default:
System.out.println("Enter a Valid Value");
}
}while(i==1);
}
}
Hope this solves your query.
You can do some thing
private static Person [] addPersons(Person[] persons, Person personToAdd) {
int currentLenght = persons.length;
Person [] personsArrayNew = Arrays.copyOf(persons, currentLenght +1);
personsArrayNew[currentLenght] = personToAdd;
return personsArrayNew;
}
You can create array with variable containing length. Like new int[n]. And pass n dynamically as argument to method. You can also create array with maximum size you can possibly need. And also create variable to track current size. depends on what your usage is.

arraylist to array unique order

So I'm trying to go through an arraylist of objects that all have a certain strength value and depending on their strength value, they go into the bigger 2d array based on that. So if their strength value is 0 then they go in the 0th array of the bigger one and this is what my code looks like so far
private ArrayList<Battleable> arr;
public BattleDeck() {
arr = new ArrayList<Battleable>();
for (Battleable creature: arr){
arr.add(creature);
}
}
public Battleable[][] export2Darray() {
//returns a two-dimensional ragged array where each row
// contains a deep copy of all of the Battleable objects
// in the BattleStack with the corresponding Level value
Battleable[][] retVal = new Battleable[10][];
int k = 0;
for (int i = 0; i<arr.size(); i++){
int levelOfObj = arr.get(i).getLevel();
if(levelOfObj == k) {
//insert it into retVal[0][0]
}
}
}
return retVal;
}
and I was wondering how I would do that? How do i syntax-tically say "get the obj that has strength 0 and put it in position 0 0 of my 2d array
A solution using Java 8 streams:
// group Battleables ArrayList by strength
Map<Integer, List<Battleable>> map =
arr.stream().collect(Collectors.groupingBy(Battleable::getStrength));
The result is a Map containing the Battleables as Lists with their strength as their key.
If you need the result as a jagged 2D array, sort the entries like this:
final Battleable[][] arrays = new Battleable[10][];
map.entrySet().forEach(entry -> {
arrays[entry.getKey()] = entry.getValue().toArray(new Battleable[entry.getValue().size()]);
});
Since arrays are of fixed size in Java, there is no clean way to add items to an array. You can resize the array each time by creating a new array each time, one larger than the last, and copying the data from the old array to the new array, but that would be messy and you would be reinventing a wheel called ArrayList. Modus Tollens has a good answer, but it uses some slightly advanced Java 8 concepts. Here's one way to write it without them:
public Battleable[][] export2Darray() {
Battleable[][] retVal = new Battleable[10][];
// create a map that will hold the items, arranged by level
Map<Integer, List<Battleable>> byLevel = new HashMap<>();
for (int i = 0; i < 10; i++) {
// initialize all levels with empty lists
byLevel.put(i, new ArrayList<>());
}
for (Battleable battleable : arr) {
int level = battleable.getLevel();
// get the list for this level and add to it
byLevel.get(level).add(battleable);
}
// Now we have a map from levels to lists of battleables;
// we need to turn each list into an array in our retVal
for (int level = 0; level < 10; level++) {
// get each list, convert it toArray and assign to slot in retVal
retVal[level] = byLevel.get(level).toArray(new Battleable[0]);
}
return retVal;
}
Here's a solution using ArrayLists, I am creating an ArrayList which will be referenced by strength, then inside of this I have another ArrayListwhich will have all of the Battleable objects of that strength level.
public ArrayList<ArrayList<Battleable>> exportBattleable() {
ArrayList<ArrayList<Battleable>> retVal = new ArrayList<ArrayList<Battleable>>();
for (int i = 0; i < arr.size(); i++){
retVal.get(arr.getLevel()).add(arr.get(i));
}
return retVal;
}
Now if you want to print all Battleable objects of strength = 3, you would do:
ArrayList<Battleable> strength3 = retVal.get(3);
for(Battleable battleable : strength3) {
System.out.println(battleable.toString());
}
This way you don't have to worry about re-sizing your arrays depending on how many Battleable objects you are adding in, same with strength levels, if you decide that instead of using strength levels from 0-9 that you wanted to use 0-20 you already have the ability to scale up or down.

How to check if a value in an Array is contained in the same array as its following one

In my Java program I have a String array of String arrays containing 3 values each.
String[][] actions =
{
new String[]{"R", "R'", "R2"},
new String[]{"L", "L'", "L2"},
new String[]{"D", "D'", "D2"},
new String[]{"U", "U'", "U2"},
new String[]{"F", "F'", "F2"},
new String[]{"B", "B'", "B2"}
};
Now I'm letting a randomizer pick 25 values out of these arrays by random and saving the results in a normal String array (let's call it results). Now I want to check if value 0 in results is contained in the same Array as value 1, meaning if value 0 is "U" and value 1 is "U'" it should re-roll the randomizer for value 1, ignoring the array value 0 is in. In the end I'd like to have an array of Strings where no String is in the same array as its following one.
Based on your comment, you might be looking for something like this?
public void mainMethod() {
...
for(int i=0; i<(results.length-1); i++) {
compare(results, i);
}
}
private void compare(String[] results, int index) {
// compare if both values are in the same array
if(getRowIndex(results[index]) == getRowIndex(results[index+1])) {
reRoll(results, (index+1)); // reroll if so
compare(results, index); // revalidate in case it re-rolls to the same array value
}
}
private void reRoll(String[] results, int index) {
//TODO
}
private void getRowIndex(...) {
//TODO
}
The final two methods are up to how you want to implement it. There are many ways...

Converting a Bidimensional Array (Numbers) Into A Dimensional Array and Viceversa on Java

I'm in need of help right now. I need to convert 2 dimensional array of numbers to a one dimensional array in Java. Can anyone help me?
Do you mean something like this?
import java.util.*;
public class Test {
public static void main(String[] args) {
String[][] data = new String[][] {
{ "Foo", "Bar" },
{ "A", "B" }
};
String[] flattened = flatten(data);
for (String x : flattened) {
System.out.println(x);
}
}
public static <T> T[] flatten(T[][] source) {
int size = 0;
for (int i=0; i < source.length; i++) {
size += source[i].length;
}
// Use the first subarray to create the new big one
T[] ret = Arrays.copyOf(source[0], size);
int index = source[0].length;
for (int i=1; i < source.length; i++) {
System.arraycopy(source[i], 0, ret, index, source[i].length);
index += source[i].length;
}
return ret;
}
}
If you want it for primitive types, you'll have to write an overload for each primitive type, but you can use new int[size] instead of Arrays.copyOf at that point.
A Java 8 solution could look something like this:
import java.util.stream.Stream;
public class ArrayConverter {
public static String[] flatten(String[][] array) {
// Create a stream of the given array
return Stream.of(array)
// Map each of its elements to a stream (thus creating a
// one-dim-array inside the stream, so to say)
.flatMap(Stream::of)
// Retrieve the stream as array, explicitly calling String to
// keep the type
.toArray(size -> new String[size]);
}
}
I consciously left out generic types in this example since it makes the Array Initialization somewhat confusing. Let me know if you need it tho.
Notably; if you want to use this conversion for Arrays of primitive types you should use the corresponding flat Methods of the Stream Class.
E.g. if you're using int-Arrays use:
Stream.flatMapToInt(...)
to retrieve an IntStream with actual primitive int-Values thus dodging autoboxing into Integer Objects.
JavaDoc of Stream for reference

Categories