java array nullpointer - java

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.

Related

Java with ArrayLists the index of function

is there a way with the index of function to return the index of a value that is part of a class like just one field of the bigger structure.. I got a simple contact class and I want to return the index when the id is a certain value .. should I be using a different structure than an arrayList it is doing most of what I want but the index of function is frustrating
I think the easiest way is to just iterate over the array, and check the condition with "if". That will be O(n).
You can use the Predicate method explained here.
Optional<Integer> indexOfMatch = IntStream.range(0, yourList.size())
.filter(i -> valueYouAreLookingFor.equals(yourList.get(i).getFieldYouAreChecking()))
.findFirst();
Or if the field holds a primitive value:
Optional<Integer> indexOfMatch = IntStream.range(0, yourList.size())
.filter(i -> valueYouAreLookingFor == yourList.get(i).getFieldYouAreChecking())
.findFirst();
If there is an element in the list that matches your predicate, indexOfMatch will have the index of that element. If not, indexOfMatch will be an empty Optional.
Regarding whether an ArrayList is the appropriate structure, generally if you are working with a list of values, an implementation of List is what you want. Whether it should be ArrayList or some other implementation depends on details of what you are doing with the list. For small list sizes, it often doesn't really matter which implementation you use.
well I switched to a vector from an array list but it did not really help but I did use a loop and the list size and just put the contact in a container each time so I could do my comparison it was kinda messy but I got the index that way.
static int SearchForContact(String ContactID) {
int temp = -1;
Contact searchCon;
for (int z = 0 ; z < contactVector.size(); z++)
{searchCon = contactVector.get(z);
if(searchCon.getId() == ContactID)
{temp = z;}
}
if (temp == -1) {
throw new IllegalArgumentException("Contact not found");
}
return temp;
}
I am iterating over the ArrayList and seeing whether the current value is the id value you want.
int yourValue = 25; //I am assuming it to be an int of value 25, you can keep it whatever you want.
for (int i = 0; i < yourArrayList.size(); i++)
{
if (yourArrayList.get(i) == yourValue)
{
return i; //returning the index value
}
}
return null; //this will run if the value doesn't exist.
Obviously, this would need to be inside a method that returns an integer that is the index. Above, yourArrayList is the ArrayList you are using, and yourValue is the value you need to find. It doesn't have to be an int.

How can I tell if the elements in an Array List are same or different?

I'm trying to verify if all the elements in an array list are same or not. This is my code:
ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(2,2,4,2));
for (int z = 0; z < arr.size(); z++) {
if(!arr.get(z++).equals(arr.get(z--))) {
System.out.println("same");
}else {
System.out.println("differnt");
}
}
Put the elements into a Set. If the resulting set has a size of 1, then all elements have been the same. One line of code, no loops, no indices, works with every collection:
boolean allTheSame = new HashSet<Integer>(list).size() == 1;
System.out.println(allTheSame ? "same" : "different");
(Edited:)
It might be worth noting that if the list is large, and likely contains many different elements, then constructing a Set will impose some memory overhead that can be avoided, if desired. In this case, you'd iterate over the list and compare all elements to the first one. But you should not check the elements for identity with ==. Instead, you should compare them using their equals method, or, if you graciously want to handle null entries, using Objects#equals.
An example of how to solve this efficiently and generically is given in the answer by Zabuza
There are various solutions to this.
Compare any with others
You just need to pick any element (the first, for example) and then compare this to all other elements. A single simple loop is enough:
public static <E> areElementsEquals(List<E> list) {
// Edge cases
if (list == null || list.size() <= 1) {
return true;
}
// Pick any element
E any = list.get(0);
// Compare against others
for (E other : list) {
// Use Objects#equals for null-safety
if (!Objects.equals(any, other)) {
return false;
}
}
return true;
}
Or a Stream-API version:
return list.stream()
.allMatch(other -> Objects.equals(any, other));
If you checked that any is not null, you could also use a method reference:
return list.stream()
.allMatch(any::equals);
Set
Sets do not have duplicates. You can put all your elements into a Set and check if the size is 1, then all other elements were duplicates.
return new HashSet<>(list).size() == 1;
While this code is pretty compact, I would favor the more straightforward solution of iterating. It is a bit more readable and also more efficient, since it does not have the additional overhead of setting up a set.
You only have to compare the 1st item against all the others:
int a = arr.get(0);
boolean allSame = true;
for (int z = 1; z < arr.size(); z++) {
allSame = (a == arr.get(z));
if (!allSame) break;
}
if (allSame)
System.out.println("Same");
else
System.out.println("Different");
. . . and does your code work? What sort of output do you get? Are you suffering any exceptions?
Don't declare your List as ArrayList; declare it as List. Don't call a List arr; it isn't an array. Call it numbers or something like that.
Why have you got the bang sign/not operator in line 3? I think that shouldn't be there.
If you think about the different kinds of collection/data structure available, which you can read about here, you will find a collection type whose size() method will tell you how many distinct elements you have.
You just have to compare the current element with the next, if they are different that means you don't have all elements the same:
for(int i = 0; i < list.size() - 1; i++) {
if (list.get(i) != list.get(i + 1)) {
return false; // elements are different
}
}
return true; // all element are the same
Try this :
String first = arr.get(0);
boolean allTheSame = true;
if (arr.size() > 1) {
for (int z = 1; z < arr.size(); z++) {
if (!arr.get(z).equals(first)) {
allTheSame = false;
break;
}
}
}
A method use BitSet to judge are all elements in list is same or not,it need less memory and run faster.
public static boolean areAllElementsSame(List<Integer> numbers) {
BitSet set = new BitSet();
numbers.forEach(new Consumer<Integer>() {
#Override
public void accept(Integer integer) {
set.set(integer);
}
});
return set.cardinality() == 1;
}
This method can also used to figure out how many different elements.
same is a flag that stores the result we intend.
uv is the uniformality variable.
Object is the type of object you stored in list (the arraylist)
import java.util.*;
class Main{
public static void main(String args[]){
ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(2,2,2,2));
boolean same=true;
Object uv=arr.get(0);
for (Object i: arr){
if(!i.equals(uv)){
same=false;
break;
}
}
System.out.print("Result:"+same);
}
}
You will have to check for each element, if all the elements on later indexes are same as that one or different than it.
You can do it using a nested loop like this:
public static void main(String[] args) {
// write your code here
ArrayList<Integer> arr = new ArrayList<Integer>(Arrays.asList(2,2,4,2));
boolean result=true;
for (int i = 0; i < arr.size(); i++) {
for (int j=i; j<arr.size(); j++){
if (!arr.get(i).equals(arr.get(j))){
result=false;
}
}
}
System.out.println(result);
}
the 2nd loop starts from j=i and goes till the right end of the array because you don't need to check the left side of that index as it is already checked in the previous iterations and the result would already have been updated to false.
If you want to ensure that the list contains at least two different elements, you have to "walk" the array once: you compare the first element against all others, and stop on the first mismatch. On mismatch: not all elements are the same, otherwise they are all the same!
But the initial question was a bit unclear. If you want to determine if there are no two equal elements in the array, you have to compare all entries against all others! Then you need two loops: you pick all elemenst in order, to compare them to all others (respectively to all following ones: you already compared slot 1 to all other slots, so you would only have to compare slot 2 to slot3 ... til end).
Another approach would be to use a Set implementation, for example HashSet! Sets have unique members. So when you turn your list into a set, and the set has less entries than the list, you know that the list contains duplicates.

Sum of an array from class variable 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;

Kinda new to Java and stuck with collections. Here I'm trying to generate random numbers without duplicates

This is my snippet. record[i] is an object with 2 variables id and number. And I'm getting the error unexpected type : required variable; found : value.
int Shuffle = 0;
List<Integer> randomID = new ArrayList<Integer>();
List<Integer> randomNumber = new ArrayList<Integer>();
for (int i=0;i<100 ;i++) {
randomID.add(new Integer(i));
}
Collections.shuffle(randomID);
for (int i=0;i<100000;i++) {
randomNumber.add(new Integer(i));
}
Collections.shuffle(randomNumber);
for (int i=0;i<length;i++) {
if (randomID.contains(record[i].ID)) {
randomID.indexOf(record[i].ID)=null; //ERROR : REQUIRED VARIABLE FOUND VALUE
}
}
for (int i=0;i<length;i++) {
if (randomNumber.contains(record[i].getNumber())) {
randomNumber.indexOf(record[i].getNumber())=null;
}
}
Your call to randomID.indexOf(record[i].ID) returns some value. You have put it on the left side of an equals sign, so the compiler is looking for something to which it can ASSIGN a value. It can't assign a value to a value, it must have a variable.
I suppose you might mean to assign null to the ID of that element of the array: record[i].ID = null;
Or you might need the index into randomID:
int index = randomID.indexOf(record[i].ID);
randomID.set(index, null);
but you end up with a list that has a bunch of nulls in it. Is that really what you want?
Anyway, your question was about the error. If you have a different question, ask it in a different post.
With java collections, there are several types of storage.
The List collection allows for duplicate entries.
The Set collection does not allow duplicates.
Set set = new HashSet<Integer>(); //assuming you want Integer
int randomNumberCount = 10
while(set.size() < randomNumberCount) {
int temp = Math.random() * 100;
set.add(new Integer(temp));
}
Adding entries to a set that already exist will just replace it.

remove specific object does not work in Java ArrayList

I have an ArrayList of object containing a reference to their parent object.
I am trying to remove every objects within a specific parent (so equals to the parent object).
If I do:
System.out.println(parent);
my console output:
ParentObject#1f8166e5
if I do:
for(int i = 0; i < array.size(); i++){
if(array.get(i).getParent().equals(parent)){
array.remove(i);
}
}
And (test)
for(int i = 0; i < array.size(); i++){
if(array.get(i).getParent().equals(parent)){
System.out.println(parent + ":" + array.get(i).getParent());
}
}
My console output something like:
ParentObject#1f8166e5:ParentObject#1f8166e5
What's wrong with the snippet above?
Why array.remove(i) did not work?
I suspect the problem is that after you've removed element i (which moves everything after it up the list - the element at index n + 1 now has index n etc) you're then skipping the next element. So if you have two consecutive elements to remove, you're missing the second one. The simplest fix is to work from the end:
for (int i = array.size() - 1; i >= 0; i--) {
if (array.get(i).getParent().equals(parent)) {
array.remove(i);
}
}
EDIT: As noted in another answer, it's generally better to use an iterator for removal anyway. In your case, this would look like this:
// We don't know what the Foo type is...
for (Iterator<Foo> iterator = array.iterator(); iterator.hasNext(); ) {
Foo element = iterator.next();
if (element.getParent().equals(parent)) {
iterator.remove(); // Note: *not* array.remove(...)
}
}
You can't remove objects while iterating. You should use Iterator if you want to remove element while iterating

Categories

Resources