for example, I have a list of integer variables
int CLUTCH_CASE = 8;
int CS20 = 6;
int DANGER_ZONE_CASE = 6;
int TOTAL_CASE = 0;
I have an array:
int CaseValue[] = {CS20, CLUTCH_CASE, DANGER_ZONE_CASE};
and I output the value of total cases, which is going to be:
for (int counter=0;counter<CaseValue.length;counter++) {
TOTAL_CASE += CaseValue[counter];
}
System.out.println("You have "+CaseValue.length+" CSGO Cases");
System.out.println("You have a total of "+TOTAL_CASE+" CSGO Cases:");
Output:
You have 3 CSGO Cases
You have a total of 20 CSGO Cases:
yet I also want to output the name.
Example:
(CASENAME are just placeholders for this example. I wanted to use CaseValue[].NAME even that does not exist since it's an example)
for (int counter2=0;counter2<CaseValue.length;counter2++) {
System.out.println(CASENAME+": "+CaseValue[counter2]);
}
My expected and wanted output to be:
CLUTCH_CASE: 8
CS20: 6
DANGER_ZONE_CASE: 6
Is there any way to output the name of the integer variable?
There is no command in Java to access the variable name.
You could use a map (like stated in other answers), but I'd also like to present a simple possibility that is possible without advanced features of Java.
What you could do is the following:
String[] caseName = {"CS20", "CLUTCH_CASE", "DANGER_ZONE_CASE"};
After that you can do:
for (int i=0; i<CaseValue.length; i++) {
System.out.println(caseName[i] + ": " + CaseValue[i]);
}
Use a Map.
Map<String, Integer> ma = new Hashmap()
for (int counter=0;counter<CaseValue.length;counter++) {
TOTAL_CASE += CaseValue[counter];
ma.put(<your_key>, <your_value>)
}
I still dont understand your code completely. So cannot give you a full working snippet. I have however added a snippet on how you could possibly use a map. Store the key as the name that you want and its corresponding value in that key of the map.
You need to use java.lang.Class and its getFields() method to return an array of java.lang.reflect Field[] class object
Below will give you an idea of how, go take a look in the API docs for a better more suitable set of methods to design the process with a List or Set to use contains() method so you can put it in a class and call when you want in a program.
import java.lang.Class;
import java.lang.reflect.*;
Field[] varFset = ((java.lang.Class)this).getFields();
// compare names processing code over the array here
String varname = varFset[x].getName();
You could use a HashMap.
enum CaseType {
CLUTCH_CASE,
CS20,
DANGER_ZONE_CASE;
}
Map<CaseType, Integer> map = new HashMap<>(3);
map.put(CaseType.CLUTCH_CASE, 8);
map.put(CaseType.CS20, 6);
map.put(CaseType.DANGER_ZONE_CASE, 6);
map.forEach((key, value) -> System.out.println(key.name() + ": " + value));
I have a class with a 2D array which stores values that have been randomly generated by a method. I want to use this 2D array to pass its values to be used by the 'GenerateGradesUranium()' method in another class.
The class with the array: (To my understanding, this Class is fine for the purpose I want it to achieve).
public class GenerateUranium
{
int[][] tray = new int[5][3];
private int grading = 0;
private Random randomGenerator;
public GenerateUranium()
{
randomGenerator = new Random();
}
public void generateSample()
{
for (int i = 0; i < tray.length; i++)
{
for (int j = 0; j < tray[i].length; j++)
{
grading = randomGenerator.nextInt(50);
tray[i][j]=grading;
}
}
printTray(tray);
}
The class with the method that I want to use the 2d array in. (Where I'm completely lost).
import java.util.ArrayList;
public class LithiumGradingUranium
{
private ArrayList highGradeUranium;
private ArrayList lowGradeUranium;
public LithiumGradingUranium()
{
}
public void generateGradesUranium() // This is the method where I want to use the Array as a parameter
{
}
So the 2D array is used as a parameter in 'generateGrades()' and then need to be split between two array lists based on the value being > 25 (highGrade) or ≤ 25 (lowGrade)
I've tried a variety of ways to get the array list from the 1st class to work in the 2nd but they haven't worked. I've looked at book references and video tutorials but they often only deal with non-2d Arrays or using the array within the same class. I've new at Java and I've been thrown in the deep end, I'd really appreciate the help in this so that I can move on to figuring out and completing the rest of my program. Not knowing how to make use of the initial array is crippling my ability to make the program work as intended. Trying to have a 2D array turn into 2 Array Lists further complicates the matter.
Many Thanks
You pass 2D arrays in a similar way you pass 1D arrays say:
public void generateGrades(int[][] tray)
{
// Now here's some pseudo code on how to iterate the tray
for(int i = 0; i < tray.length; ++i)
{
for(int j = 0; j < tray[0].length; ++j)
{
int trayElement = tray[i][j];
if(trayElement less than 25)
{
// add it to the lower grade list
}
else
{
// add it to the higher grade list
}
}
}
}
One more thing, when using generics don't use what's called raw types e.g.
ArrayList
Instead specify the type
ArrayList<Integer>
Using java 8 streams, you can also write:
Map<Boolean, List<Integer>> result =
Arrays.stream(tray).flatMapToInt(Arrays::stream).boxed()
.collect(Collectors.groupingBy(d -> d > 25));
will give you a java.util.HashMap with Boolean keys like the following:
{false=[5, 11, 25, 10, 14, 20, 15, 3, 6, 9], true=[38, 43, 38, 28, 40]}
So the low grades are under false key and the high grades are under true key in the map and are easily retrievable.
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.
Attempting to tidy up code, originally I was using this method of writing to arrays, which is ridiculously long when I have to repeat it 20 times
if (ant.getAntNumber() == 3)
{
numbers3.add(ant.getCol());
numbers3y.add(ant.getRow());
}
if (ant.getAntNumber() == 4)
{
numbers4.add(ant.getCol());
numbers4y.add(ant.getRow());
}
I attempted to use a for loop to do it but I cant figure out how to add to the array using the string value, because it thinks its a string rather than trying to use the array
for (int j = 0; j<maxAnts; j++)
{
String str = "numbers" + j;
String str2 = "numbers" + j + "y";
//this part doesnt work
str.add(ant.getCol());
}
Any suggestions would be helpful
In Java, you cannot use the value of a String object to reference an actual variable name. Java will think you're attempting to to call add on the String object, which doesn't exist and gives you the compiler error you're seeing.
To avoid the repetition, you need to add your Lists to two master lists that you can index.
In your question, you mention arrays, but you call add, so I'm assuming that you're really referring to Lists of some sort.
List<List<Integer>> numbers = new ArrayList<List<Integer>>(20);
List<List<Integer>> numbersy = new ArrayList<List<Integer>>(20);
// Add 20 ArrayList<Integer>s to each of the above lists in a loop here.
Then you can bounds-check ant.getAntNumber() and use it as an index into your master lists.
int antNumber = ant.getAntNumber();
// Make sure it's within range here.
numbers.get(antNumber).add(ant.getCol());
numbersy.get(antNumber).add(ant.getRow());
How about this?
Ant[] aAnt = new Ant[20];
//Fill the ant-array
int[] aColumns = new int[aAnt.length];
int[] aRows = new int[aAnt.length];
for(int i = 0; i < aAnt.length; i++) {
aColumns[i] = aAnt[i].getCol();
aRows[i] = aAnt[i].getRow();
}
or with lists:
List<Integer> columnList = new List<Integer>(aAnt.length);
List<Integer> rowList = new List<Integer>(aAnt.length);
for(Ant ant : aAnt) {
columnList.add(ant.getCol());
rowList.add(ant.getRow());
}
or with a col/row object:
class Coordinate {
public final int yCol;
public final int xRow;
public Coordinate(int y_col, int x_row) {
yCol = y_col;
xRow = x_row;
}
}
//use it with
List<Coordinate> coordinateList = new List<Coordinate>(aAnt.length);
for(Ant ant : aAnt) {
coordinateList.add(ant.getCol(), ant.getRow());
}
A straight-forward port of your code would be to use two Map<Integer, Integer> which store X and Y coordinates. From your code it seems like ant numbers are unique, i.e., we only have to store a single X and Y value per ant number. If you need to store multiple values per ant number, use a List<Integer> as value type of the Map instead.
Map<Integer, Integer> numbersX = new HashMap<Integer, Integer>();
Map<Integer, Integer> numbersY = new HashMap<Integer, Integer>();
for(Ant ant : ants) {
int number = ant.getAntNumber();
numbersX.put(number, ant.getCol());
numbersY.put(number, ant.getRow());
}
I have a List with say size n, and I have to dynamically create n variables ie i want to dynamically create the variables depending upon the size of the list. How can i achieve this?
Say i have List as List<Integer> year with n elements in it;
then i have to create the n Integer variables from the above list.
EDIT : If i have list with 3 elements in it the i want to create 3 variables like
a = list(0);
b = list(1);
c = list(2);
like this the list may have any number of elements then i have to create those many variables. Hope I am clear now.
thanks.
You can not create n local variables as you seem to suggest. (What would their names be?)
You need to store the variables (or rather integer values) in a List or some other Collection, and populate them within a loop:
int n = year.size();
List<Integer> theIntegers = new ArrayList<Integer>(n);
for (int i = 0; i < n; i++)
theIntegers.add(i);
gives you year.size() number of integers (0, 1, 2, ...).
You can then access the integers through
theIntegers.get(4);
if you want to read the integer with index 4. and
theIntegers.set(4, 10);
if you want to update the integer with index 4, to the value 10.
You could in this case also create an array:
int[] ints = new int[year.size()];
for (int i = 0; i < ints.length; i++)
ints[i] = i;
There is no way I know of in Java to dynamically add variables to a scope. You can use a map as a type of variable... well, mapping instead:
final List<Integer> years = getYearList();
final Map<String, Integer> yearMapping = new HashMap<String, Integer>();
for(int year : years)
{
final String name = generateNameForYear(year);
yearMapping.add(name, new Integer(year));
}
// Later... Get "variables" out of the map:
final String variableName = "fooYear";
if (yearMapping.containsKey(variableName))
{
final Integer variableValue = yearMapping.get(variableName);
}
else
{
// "variable" does not exist.
}