Java ArrayList replace at specific index - java

I need help with this java please. I created an ArrayList of bulbs, and I'm trying to replace a bulb at specific index with another bulb. So with the following heading, how do I proceed?
public void replaceBulb(int index, Bulbs theBulb) {
}

Check out the set(int index, E element) method in the List interface

You can replace the items at specific position using set method of ArrayList as below:
list.set( your_index, your_item );
But the element should be present at the index you are passing inside set() method else it will throw exception.
Also you can check oracle doc here

Use the set() method: see doc
arraylist.set(index,newvalue);

Use ArrayList.set

public void setItem(List<Item> dataEntity, Item item) {
int itemIndex = dataEntity.indexOf(item);
if (itemIndex != -1) {
dataEntity.set(itemIndex, item);
}
}

Lets get array list as ArrayList and new value as value
all you need to do is pass the parameters to .set method.
ArrayList.set(index,value)
Ex -
ArrayList.set(10,"new value or object")

Related

How do you find the index of the value(a String Value) from an arrayList? [duplicate]

For an Android app, I have the following functionality
private ArrayList<String> _categories; // eg ["horses","camels"[,etc]]
private int getCategoryPos(String category) {
for(int i = 0; i < this._categories.size(); ++i) {
if(this._categories.get(i) == category) return i;
}
return -1;
}
Is that the "best" way to write a function for getting an element's position? Or is there a fancy shmancy native function in java the I should leverage?
ArrayList has a indexOf() method. Check the API for more, but here's how it works:
private ArrayList<String> _categories; // Initialize all this stuff
private int getCategoryPos(String category) {
return _categories.indexOf(category);
}
indexOf() will return exactly what your method returns, fast.
ArrayList<String> alphabetList = new ArrayList<String>();
alphabetList.add("A"); // 0 index
alphabetList.add("B"); // 1 index
alphabetList.add("C"); // 2 index
alphabetList.add("D"); // 3 index
alphabetList.add("E"); // 4 index
alphabetList.add("F"); // 5 index
alphabetList.add("G"); // 6 index
alphabetList.add("H"); // 7 index
alphabetList.add("I"); // 8 index
int position = -1;
position = alphabetList.indexOf("H");
if (position == -1) {
Log.e(TAG, "Object not found in List");
} else {
Log.i(TAG, "" + position);
}
Output: List Index : 7
If you pass H it will return 7, if you pass J it will return -1 as we defined default value to -1.
Done
If your List is sorted and has good random access (as ArrayList does), you should look into Collections.binarySearch. Otherwise, you should use List.indexOf, as others have pointed out.
But your algorithm is sound, fwiw (other than the == others have pointed out).
Java API specifies two methods you could use: indexOf(Object obj) and lastIndexOf(Object obj). The first one returns the index of the element if found, -1 otherwise. The second one returns the last index, that would be like searching the list backwards.
There is indeed a fancy shmancy native function in java you should leverage.
ArrayList has an instance method called
indexOf(Object o)
(http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html)
You would be able to call it on _categories as follows:
_categories.indexOf("camels")
I have no experience with programming for Android - but this would work for a standard Java application.
Good luck.
the best solution here
class Category(var Id: Int,var Name: String)
arrayList is Category list
val selectedPositon=arrayList.map { x->x.Id }.indexOf(Category_Id)
spinner_update_categories.setSelection(selectedPositon)
Use indexOf() method to find first occurrence of the element in the collection.
The best way to find the position of item in the list is by using Collections interface,
Eg,
List<Integer> sampleList = Arrays.asList(10,45,56,35,6,7);
Collections.binarySearch(sampleList, 56);
Output : 2

How to remove the last string in an array element using parameters of another method named removeLast()

Here is the question of exercise and my code:
Create the method public static void removeLast(ArrayList strings) in the exercise template. The method should remove the last value in the list it receives as a parameter. If the list is empty, the method does nothing.
public static void main(String[] args) {
// Try your method in here
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("First");
arrayList.add("Second");
arrayList.add("Third");
System.out.println(arrayList);
removeLast(arrayList);
System.out.println(arrayList);
}
public static void removeLast(ArrayList<String> strings) {
strings.remove("Second");
strings.remove("Third");
}
The sample output should look similar to the following:
[First, Second, Third]
[First]
What does the exercise mean by if the list is empty, the method does nothing?
I also keep getting error from local test saying the following:
removeLast method should remove the last element of the list.
Could someone help please?
"If the list is empty, the method does nothing" --> Check if the list is empty or not, if empty just return nothing , else delete last element(as per your requirement)
Example:
public static void removeLast(ArrayList<String> strings) {
if( (strings.isEmpty())) {
return;
}
else {
strings.remove(strings.size()-1);
}
}
There is no mathematical way to check if arrayList is empty or not.
a. Either you have to check with method isEmpty() [or]
b. check with array list size is greater than zero.
In application programming you have to check if array list is NOT NULL and the list is NOT EMPTY.
you can first simply check list is empty of not if it is not empty than you can call size() methos it give last index number of list and simply you can call remove(int) method to remove last element.
public static void removeLast(ArrayList<String> strings) {
if(strings.isEmpty()) {
} else {
strings.remove(strings.size()-1);
}
}

How can I check if an element exists at an index in a LinkedList

I have class called Modul and am adding elements of them to my LinkedList. Now I want to write a method where I input an Integer and check if there is an element at that index of the list or if it is empty. if there is a element i will return it and if not i want to return null and an error message.
I have thought of using an if-statement, but ultimately can't think of a method that checks whether or not an element is present. Now I thought of using try-catch but I don't know what kind of error I would need to catch.
import java.util.LinkedList;
public class Modulhandbuch {
private String nameStudienordnung;
private LinkedList<Modul> liste;
public Modulhandbuch(String nameStudienordnung) {
this.nameStudienordnung = nameStudienordnung;
liste = new LinkedList<Modul>();
}
public void einfuegenModul(Modul m) {
liste.add(m);
}
public int anzahlModule() {
return liste.size();
}
public Modul ausgebenModul(int i) {
try {
return liste.get(i);
}catch() //I don't know what error i would need to catch
}
}
You get a null pointer exception if you give the method an integer value that is bigger than the size of the list, because this index does not exist, so you need to check that. The method below correctly handles that case.
public Modul ausgebenModul(int i) {
if (i >= anzahlModule)
return null;
else
return liste.get(i);
}
indexing a linked list is waste of memory it takes O(n) to get to that index in a linkedList if you insist on this then you can add a property to the Node int index and through the constructer Node() increase this and set that instance to that value now there are few little problems to this what happens when you remove a Node at the Start ? yeah big problem the whole list must be reindexed thats makes the process of remove from Start which is O(1) a O(n) operation
you can do a trick to index it or give an illusion of been indexed is just don't do it when you ask for list(6) the iterator counts 6 Nodes Starting with 0 and stop at that Node

Trying to print an array

I need some help with java and returning a result from an array.
My array list stores orders from a restaurant (created by the Order Class). The Deliverylog Class (which creates the array lists) then has a method for adding the orders to an array list called waitingList.
Each order has a reference number aswell ass details of it delivery time and so on ..
What im trying to do , but havent got a clue is to , is to create a method with a parameter (int ref) that will search the array list for an item with the same reference number as the one entered. When it finds it it returns the order , otherwise it returns null.
Any help is appriciated.
code
/**
* Show a order.
* #param refnum The reference number of the order to be shown
*/
public void findOrderWaiting(int refnum)
{
if(refnum < 0) {
// This is not a valid reference number
}
else if(refnum <= numberOfOrders()) {
// This is a valid reference number
System.out.println(waitingList.get(refnum));
}
else {
// This is not a valid reference number
}
}
You know arrayList has a method to find an item inside:
//a is an arraylist
//filling the list here is omitted
//o is the object to find its index
int ind=a.indexOf(o);
int indexOf(Object o) is already-invented so you dont have to make a method. If you want this for learning purposes, you can search hashing techniques from internet but you are using arrayList and the easiest thing is the indexOf() method.
HashTable is more flexible by giving you freedom to search for an item or a key (you give key and get item or you give item and get its key)(key can be an object too!)
Well, you could loop through the array using a standard for loop:
for(int i=0; i<array.length; i++){
if(array[i].intPart == ref) return array[i];
}
return null;
Hope that helps!
for(String s: restaurentOrders){
if(s.equalsIgnoreCase()){
//You have it..
}
}
If u are storing your array/Arraylist in restaurentOrders. Hope it helps

Better way to find index of item in ArrayList?

For an Android app, I have the following functionality
private ArrayList<String> _categories; // eg ["horses","camels"[,etc]]
private int getCategoryPos(String category) {
for(int i = 0; i < this._categories.size(); ++i) {
if(this._categories.get(i) == category) return i;
}
return -1;
}
Is that the "best" way to write a function for getting an element's position? Or is there a fancy shmancy native function in java the I should leverage?
ArrayList has a indexOf() method. Check the API for more, but here's how it works:
private ArrayList<String> _categories; // Initialize all this stuff
private int getCategoryPos(String category) {
return _categories.indexOf(category);
}
indexOf() will return exactly what your method returns, fast.
ArrayList<String> alphabetList = new ArrayList<String>();
alphabetList.add("A"); // 0 index
alphabetList.add("B"); // 1 index
alphabetList.add("C"); // 2 index
alphabetList.add("D"); // 3 index
alphabetList.add("E"); // 4 index
alphabetList.add("F"); // 5 index
alphabetList.add("G"); // 6 index
alphabetList.add("H"); // 7 index
alphabetList.add("I"); // 8 index
int position = -1;
position = alphabetList.indexOf("H");
if (position == -1) {
Log.e(TAG, "Object not found in List");
} else {
Log.i(TAG, "" + position);
}
Output: List Index : 7
If you pass H it will return 7, if you pass J it will return -1 as we defined default value to -1.
Done
If your List is sorted and has good random access (as ArrayList does), you should look into Collections.binarySearch. Otherwise, you should use List.indexOf, as others have pointed out.
But your algorithm is sound, fwiw (other than the == others have pointed out).
Java API specifies two methods you could use: indexOf(Object obj) and lastIndexOf(Object obj). The first one returns the index of the element if found, -1 otherwise. The second one returns the last index, that would be like searching the list backwards.
There is indeed a fancy shmancy native function in java you should leverage.
ArrayList has an instance method called
indexOf(Object o)
(http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html)
You would be able to call it on _categories as follows:
_categories.indexOf("camels")
I have no experience with programming for Android - but this would work for a standard Java application.
Good luck.
the best solution here
class Category(var Id: Int,var Name: String)
arrayList is Category list
val selectedPositon=arrayList.map { x->x.Id }.indexOf(Category_Id)
spinner_update_categories.setSelection(selectedPositon)
Use indexOf() method to find first occurrence of the element in the collection.
The best way to find the position of item in the list is by using Collections interface,
Eg,
List<Integer> sampleList = Arrays.asList(10,45,56,35,6,7);
Collections.binarySearch(sampleList, 56);
Output : 2

Categories