Sum of an array from class variable java - java

I just started OOP java and im struggling with getting a sum of my class type elements from an array. Can anyone help me?
hwComponents is a list type of a class HardwareComponent. Any help would be appreciated.
private Collection<HardwareComponent> hwComponents = new ArrayList<>();
public float calculatePrice()
{
float sum=0;
for (int i=1;i < hwComponents.size(); i++)
sum+= hwComponents.get(i); //The method get(i) is undefined for this type
return sum;
}

A Collection doesn't have a get(index) method.
Store your ArrayList in a List variable instead:
private List<HardwareComponent> hwComponents = new ArrayList<>();
Also note that the indices of your loop should begin at 0.
As an alternative, you can use an enhanced for loop, which doesn't require the get method:
for (HardwareComponent hc : hwComponents) {
sum+= hc.getSomeProperty(); // note that HardwareComponent cannot be added to
// a float (or to anything else for that matter, so you probably
// intended to call some method of your class which returns a float
}

If you don’t want to change the type of your array/collection, you just need to iterate through the collection in the collections defined order:
sum = 0;
for( HardwareComponent hc: hwComponents)
sum += hc.cost;
return sum;

Related

cannot append to my array during a for loop

I am currently learning JAVA using Aleks Rudenko book, and as a newbie in JAVA I still cannot figure out simple compilation errors. I tried to create a simple code that takes an array X and multiply every single term of it by Y. Finally, the array*Y should be printed out as follows:
public class CurrencyConverter {
double[] answers = new double[] {};
public double[] Times2 (double[] x, double y) {
for (int i=1; i<x.length+1;i++) {
answers.add(x[i]*y);
}
return answers;
}
public static void main(String[] args) {
CurrencyConverter cc = new CurrencyConverter();
double [] rates= new double[] {63,3.0,3.0,595.5,18.0,107.0,2.0,0.0};
System.out.println(cc.Times2(rates,2));
}
}
the error message is
error: cannot find symbol
answers.add(x[i]*y);
^
symbol: method add(double)
location: variable answers of type double[]
1 error
I cannot figure out what is the reason for this compilation error. Thanks for the help !
add is not defined for arrays. If you want to add elements, use List.
There are several ways to fix your code:
a) use List:
import java.util.*;
List<Double> list = new ArrayList<Double>();
public List<Double> Times2 (double[] x, double y) {
for (int i=0; i<x.length;i++) {
list.add(x[i]*y);
}
return list;
}
b) Don't add elements, just write them into array:
double[] answers;
public double[] Times2 (double[] x, double y) {
answers = new double[x.length];
for (int i=0; i<x.length;i++) {
answers[i] = x[i]*y;
}
return answers;
}
..Also, watch out for the array index out of bounds. First element has index 0 and last item has index length - 1.
And one last thing, you will probably encounter problem with printing your results.
If you want to use list, use System.out.println(cc.Times2(...).toString()); and if you want to use array, use System.out.println(Arrays.toString(cc.Times2(...)));
Better to use a while loop, instead of a for loop, for this use case. And use a Vector:
Vector<Object> answers = new Vector<Object>();
You are using . dot operator on an array. answers is an array and its values can be accessed like answers[0] -> first element or answers[9] -> gives 9th element. Had answers been an object with say a variable called status, then you would access status from answers as answers.status
Similar if answers have method say bestAnswer() then you would access it as answers.bestAnswer()
And if you want to hold a bunch of objects of your custom type Answer in an array then you would instantiate each Answer object first and add it to the array answers array as:
Answer firstAnswer = Answer();
Answer secondAnswer = Answer();
...
answers[0] = firstAnswer;
answers[1] = secondAnswer;
...
Arrays in java don't have any methods. You access stuff by index. Your code should look
public static class CurrencyConverter {
public double[] Times2(double[] x, double y) {
double[] answers = new double[x.length];
for (int i=0; i < x.length; i++) {
answers[i] = x[i] * y;
}
return answers;
}
}
Notice that the for loop starts with i as 0. the first index of an array is always 0, not 1. the answers array is init'ed inside the method as it's best to keep variables hidden (scoped) from things that don't need them. it's also init'ed with the size it needs to be.
Some of the other answers here say to use stuff based on java.util.AbstractCollection. While you could but there's no good reason for extra overhead for something simple like this.

Can Java use user defined object as an index of 2D array key?

array[obj][obj] = 1;
I want to create 2D array whose index is user defined object. How to do this? or there is some other data structure available to do this?
No the Java Language Specification states that an array can only be accessed using an int. Though thanks to primitive type promotion, short, char and byte can be used as well as they get automatically converted to int.
To solve your problem: You can store an int index inside your object and then use that to access the array.
array[obj.getIndex()][obj.getIndex()] = 1;
If you cannot directly influence the code of the user defined object, force the user to implement an interface that requires the getIndex() method.
interface ArrayIndexable {
int getIndex();
}
Alternatively if you cannot force the user to implement the interface, then you can maintain some sort of index using a map that maps the object to an int.
int x = ...;
int y = ...;
int[][] array = new int[x][y];
Map<SomeClass, Integer> index = new HashMap<>();
for(int i = 0; i < Math.max(x, y); i++) {
SomeClass m = ...; // object associated with i
index.put(m, i);
}
SomeClass obj = ...;
// accessing the array
array[index.get(obj)][index.get(obj)] = 1;
In an array, the index can be only one of the following short, byte, char or int.
For your use case, you might want to use a HashMap, it is a collection of keys and corresponding values. Key can be any user defined object and value can also be any defined object.
A simple hashmap example where keys are of type String and values are of type Double.
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Zara", new Double(3434.34));
hm.put("Mahnaz", new Double(123.22));
hm.put("Ayan", new Double(1378.00));
hm.put("Daisy", new Double(99.22));
hm.put("Qadir", new Double(-19.08));
No, it array indices can be only integer in java but there is a way to achieve this.
Associate array indices to object using hashmap, and for each value retrive the index value using object as a key and use it as index.
//This example will help you
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class Experiment {
public static void main(String[] args) {
int a[]=new int[10];
HashMap<Student,Integer>map=new HashMap<>();
for (int i = 0; i < 10; i++) {
map.put(new Student(),i);
a[i]=i;
}
ArrayList al=new ArrayList(map.keySet());
int x;
for (int i = 0; i < al.size(); i++) {
x=map.get(al.get(i));
System.out.print(a[x] + " " + " ");
}
}
}
class Student{
int a,b;
}
But do remember hashmap doesn't preserve the insertion order.
Please comment if you face any problem or accept if works.
You can go for treemap if you want insertion order.

Conceptual understanding about Array Lists in methods

For an assignment, we had to write a method sum that expects a List as a parameter. The method returns an int representing the sum of the integers in the list.
Would the code turn out to be:
public int getSum (List <Integer> list) {
int sum = 0;
for (int i = list)
sum = sum + i;
return sum;
}
I'm confused on when to use Integer vs int in this scenario. Thanks in advance!
Edit: If possible, could you guys edit my code?
No need to confuse. Your code seems correct to me. In java Wrapper classes are provided for premitive types. Java manages boxing/unboxing for those premitive type variable to their respective wrapper classes. e.g. Integer for int Long for long etc.
Usually Wrapper classes (Integer) turns to useful when considered for comparing object or to perform some class level operation such as equals() and hashCode() method, and also Collection framework require Object type not premitive type.
Integer is a Object/Wrapper Class int is a primitive type, Here is the link for you to understand more
Collections in java are generic class that you can use them to collect any object but not primary types. So you cannot use List<int>. If you are interested in using collections such as List, you have to use Integer.
public int getSum (List <Integer> list) {
int sum = 0;
for (int i : list)
sum = sum + i;
return sum;
}
Java collections use autoboxing concept. So for most cases you don't need to worry about the conversion. This is internally handled (i.e. from boxed to unboxed(primitive) type).
Below is the snippet:
public int getSum (List<Integer> list) {
int sum = 0;
for (int elem : list)
sum += elem;
return sum;
}

java array nullpointer

I'm trying to find minimum of an array. The array contain Nodes - a node contains of an element E and a priority int. Im want to find the Node in the array with the smallest priority.
#Override
public E min() {
Node temp = S[0];
for(int i = 1; i<S.length; i++){
int prio= S[i].getPrioritet(); <-- nullpointer excp.
if(prio<temp.getPrioritet()){
temp = S[i];
}
}
return temp.getElement();
But i get an nullpointer exception when i try to use it. Does anybody know what im doing wrong?
Here is my test:
PrioritetArraySorteret<String> p = new PrioritetArraySorteret<String>();
p.insert(1, "Hello");
p.insert(3, "Hi");
p.insert(4, "Hawdy");
System.out.println(p.min());
}
start with i=0 as the array is indexed
for(int i = 0; i<S.length; i++){
int prio= S[i].getPrioritet(); <-- nullpointer excp.
if(prio<temp.getPrioritet()){
temp = S[i];
}
}
It simply means that the element at one of the indexes of array S is null. Maybe you're initialized the array at a size n but filled in less than n positions.
Altering like this will probably fix it:
for(int i = 1; i<S.length; i++){
if(S[i] != null) {
int prio= S[i].getPrioritet(); <-- nullpointer excp.
if(prio<temp.getPrioritet()){
temp = S[i];
}
}
}
That said, you might be reinventing the wheel here a bit. Using a simple ArrayList parameterized with some type that you define which encapsulates a value and priority would do. You could then have that type implement Comparable with a compareTo method that uses the priority, or write a Comparator to use for finding the minimum:
List<YourType<String>> list = new ArrayList<YourType<String>>();
Collections.min(list);
Or, if you're using a custom Comparator:
Collections.min(list, yourComparator);
-- edited for min instead of sort. Sorry.
The array S has not been initialized or one/more elements has been initialized.

How can I dynamically add items to a Java array?

In PHP, you can dynamically add elements to arrays by the following:
$x = new Array();
$x[] = 1;
$x[] = 2;
After this, $x would be an array like this: {1,2}.
Is there a way to do something similar in Java?
Look at java.util.LinkedList or java.util.ArrayList
List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.
A bit similar to the PHP behaviour is this:
int[] addElement(int[] org, int added) {
int[] result = Arrays.copyOf(org, org.length +1);
result[org.length] = added;
return result;
}
Then you can write:
x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);
System.out.println(Arrays.toString(x));
But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).
The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.
If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)
Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.
Apache Commons has an ArrayUtils implementation to add an element at the end of the new array:
/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)
I have seen this question very often in the web and in my opinion, many people with high reputation did not answer these questions properly. So I would like to express my own answer here.
First we should consider there is a difference between array and arraylist.
The question asks for adding an element to an array, and not ArrayList
The answer is quite simple. It can be done in 3 steps.
Convert array to an arraylist
Add element to the arrayList
Convert back the new arrayList to the array
Here is the simple picture of it
And finally here is the code:
Step 1:
public List<String> convertArrayToList(String[] array){
List<String> stringList = new ArrayList<String>(Arrays.asList(array));
return stringList;
}
Step 2:
public List<String> addToList(String element,List<String> list){
list.add(element);
return list;
}
Step 3:
public String[] convertListToArray(List<String> list){
String[] ins = (String[])list.toArray(new String[list.size()]);
return ins;
}
Step 4
public String[] addNewItemToArray(String element,String [] array){
List<String> list = convertArrayToList(array);
list= addToList(element,list);
return convertListToArray(list);
}
You can use an ArrayList and then use the toArray() method. But depending on what you are doing, you might not even need an array at all. Look into seeing if Lists are more what you want.
See: Java List Tutorial
You probably want to use an ArrayList for this -- for a dynamically sized array like structure.
You can dynamically add elements to an array using Collection Frameworks in JAVA. collection Framework doesn't work on primitive data types.
This Collection framework will be available in "java.util.*" package
For example if you use ArrayList,
Create an object to it and then add number of elements (any type like String, Integer ...etc)
ArrayList a = new ArrayList();
a.add("suman");
a.add(new Integer(3));
a.add("gurram");
Now you were added 3 elements to an array.
if you want to remove any of added elements
a.remove("suman");
again if you want to add any element
a.add("Gurram");
So the array size is incresing / decreasing dynamically..
Use an ArrayList or juggle to arrays to auto increment the array size.
keep a count of where you are in the primitive array
class recordStuff extends Thread
{
double[] aListOfDoubles;
int i = 0;
void run()
{
double newData;
newData = getNewData(); // gets data from somewhere
aListofDoubles[i] = newData; // adds it to the primitive array of doubles
i++ // increments the counter for the next pass
System.out.println("mode: " + doStuff());
}
void doStuff()
{
// Calculate the mode of the double[] array
for (int i = 0; i < aListOfDoubles.length; i++)
{
int count = 0;
for (int j = 0; j < aListOfDoubles.length; j++)
{
if (a[j] == a[i]) count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = aListOfDoubles[i];
}
}
return maxValue;
}
}
This is a simple way to add to an array in java. I used a second array to store my original array, and then added one more element to it. After that I passed that array back to the original one.
int [] test = {12,22,33};
int [] test2= new int[test.length+1];
int m=5;int mz=0;
for ( int test3: test)
{
test2[mz]=test3; mz++;
}
test2[mz++]=m;
test=test2;
for ( int test3: test)
{
System.out.println(test3);
}
In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.
package simplejava;
import java.util.Arrays;
/**
*
* #author sashant
*/
public class SimpleJava {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
String[] transactions;
transactions = new String[10];
for(int i = 0; i < transactions.length; i++){
transactions[i] = "transaction - "+Integer.toString(i);
}
System.out.println(Arrays.toString(transactions));
}catch(Exception exc){
System.out.println(exc.getMessage());
System.out.println(Arrays.toString(exc.getStackTrace()));
}
}
}

Categories

Resources