I have a Engineer class. And I'm creating a empty arraylist which is engineer type.
I'm creating a method to check arraylist, if arraylist isn't null it has to give me index 0. But if arraylist is null. My method has to create a new Engineer object and add to empty arraylist. After that adding, I'm expecting my method to give me index 0. But it throws IndexOutOfBoundsException. I know I missed some simple things, but I couldn't figure out how to fix.
ArrayList<Engineer> newEmptyEngineerList = new ArrayList<>();
findLastEngineer(newEmptyEngineerList);
public static void findLastEngineer(ArrayList aa){
if (aa.get(0)!=null){
System.out.println(aa.get(0));
}
else {
Engineer eng = new Engineer();
aa.add(0,eng);
System.out.println(aa.get(0));
}
}
You have to make sure that the list is not empty before calling get(0) on it.
Also avoid using raw array list and prefer interface List to its implementation when using as function parameters or return type.
public static void findLastEngineer(List<Engineer> aa) {
if (aa.isEmpty()){
aa.add(new Engineer());
}
// get and print last element
System.out.println(aa.get(aa.size() - 1));
}
Related
This seems very simple but I can't quite figure out why this isn't working.
I want to reverse the elements in my LinkedList which I have a working method for, but I can't return the value as my prof wants it to be a void method. How would I go about this?
import java.util.LinkedList;
public class ListUtil {
public static void reverse(LinkedList<String> strings) {
LinkedList<String> reverseLinkedList = new LinkedList<>();
for(int i = strings.size() - 1; i >= 0; i--) {
reverseLinkedList.add(strings.get(i));
}
strings = reverseLinkedList;
System.out.println(strings);
}
}
import java.util.LinkedList;
public class ReverseTester {
public static void main(String[] args) {
LinkedList<String> employeeNames = new LinkedList<>();
employeeNames.addLast("Dick");
employeeNames.addLast("Harry");
employeeNames.addLast("Romeo");
employeeNames.addLast("Tom");
ListUtil.reverse(employeeNames);
System.out.println(employeeNames);
System.out.println("Expected: [Tom, Romeo, Harry, Dick]");
}
}
In my ListUtil class, it does reverse the list, but doesnt return a value (as it is void) but I don't know how to go about setting employeeName in the ReverseTester class.
I know this is probably super simple but I have not been able to figure this out for the life of me, any help is greatly appreciated.
Empty and re-fill the existing list rather than replacing it.
public static void reverse(LinkedList<String> strings) {
List<String> temp = new ArrayList<>(strings); // Copy the contents of the original list. Pass the original list to constructor of our duplicate list.
strings.clear(); // Empty the original list.
for (String e : temp)
strings.addFirst(e); // Refill the original list using elements from our duplicate list.
}
Or simply
public static void reverse(LinkedList<String> strings) {
Collections.reverse(strings);
}
Non-primitive Java object are stored by reference so you don't need to return anything from ListUtil::reverse. Any changes made to the object in the function will be reflected in ReverseTester.java. This happens because, again, non-primitive Java objects are stored by reference. Basically your code does exactly what you want it to do. You make a LinkedList, populate it with items, and then reverse those items.
You will have a problem with System.out.println(employeeNames); though. Because that will just print the object's formal name and not it's contents. If you want to print the contents of a list in Java you can do:
for (String name : employeeNames) {
System.out.println(t);
}
This is my first answer so please ask any questions if I wasn't clear enough!
I still can't understand when and why should I use the "Obj obj = new Obj" and I don't get why it's so difficult for me.
In this assignment I need to create a method as it follows:
"insertSorted: This method assumes the input LinkedList is already sorted in non-descending order (i.e.,such that each element is greater than or equal to the one that is before it, and inserts the input int value into the correct location of the list. Note that the method does not return anything, but rather modifies the input LinkedList as a side effect. If the input LinkedList is null, this method should simply terminate. This is the code you're starting with:
public static void insertSorted(LinkedList<Integer> list, int value) {
/* IMPLEMENT THIS METHOD! */
}
Let alone all the complications about iterating the LinkedList list, I don't even know how to start.
Should I create a new LinkedList<Integer> newList = new LinkedList<Integer>(); so I can iterate through it right? Why though? If the list is given in the method signature should I assume that the Object is already created when the input is given in the method signature?
I am really confused. It seems that I can't quite catch the whole Object programming thing.
Obj obj = new Obj
well if want to understand the new keyword in one line its like a contract in memory area where you can store the data (thats not all but enough to start).
public static void insertSorted(LinkedList<Integer> list, int value) {
/* IMPLEMENT THIS METHOD! */
}
Now for this method you donot want to create any new object.
Q.Why?
Ans- when this method will called their is mandatory to pass some parameter to the method if not it will be a compile time error.
Passing values could be null.
Since the method returns void you should modify the list that is given as input.
I'll show you why with an example
public static void insertSorted(LinkedList<Integer> list, int value) {
LinkedList<Integer> list2 = new LinkedList<Integer>(list); //this means you are creating a new list of integers called list 2 with the same elements of the list "list" in the same order
//some code to add value to list2 maintaing the sorting
//no return needed
}
somewhere else you want to call this method
LinkedList<Integer> list = new LinkedList<Integer>();
list.Add(1);
list.Add(2);
list.Add(5);
for (Integer i : list) System.out.println(i);
//prints 1, 2 , 5
insertSorted(list,4);
for (Integer i : list) System.out.println(i);
//still prints 1, 2 , 5!
if now you run this code with a debugger and you break in the method insertSorted right after you inserted the value in list2 you will see that list "list" remains as it was at the start of the method (which is (1,2,5)) and the list "list2" will be (1,2,4,5).
But the caller method knows nothing about list2!!!
When you declare a variable within a method it dies when the method ends (unless you return it). Of course you should pay attention to the "aliasing", but this is not the case.
Your requirements are very clear: your method must modify the input rather than creating a new list.
You can't understand why you should create a new object just because you don't have to. Someone just gave you a wrong suggestion :)
Now it's up to you to iterate the list and insert the integer in the right place :)
This is an assignment, I can't post the entire code, but I really need understand what I'm doing wrong. I'm sure its a rookie mistake.:(
I had to construct a custom sort method,that sorts specific properties of my arraylist objects. I've created different Comparators to address the different elements within the objects I want sorted.
*edit added more code
sort utility method (parameters required):
public class CarManage{
private ArrayList <Car> carList; //carList defined
public class Sorts {
public static void sorts(Car[]carList, int size, Comparator <Car> someComparator) //given parameters not allowed to modify
{
//sorts arrayList(carList) objects using an insertion sort algorithm.
}
}
} //end class
I try call the sort method, to specify which properties I need sort, but alas it rejects the first parameters.
public void sortByVinNumber(){
VinNumComparator vnc = new VinNumComparator();//one of many comparators
Sorts vncSort = new Sorts();
for(int i = 0; i < carList.size(); i++){
if(vnc.compare(carList.get(i-1), carList.get(i)) > 0){
vncSort.sorts(Car[]carList, 2, vnc);//not working here rejects first parameter
///vncSort.sorts(carList,2,vnc)///doesn't work
}
}
}
I'm not sure why it won't accept my parameter? Could it be a pass-reference mistake? Or am I possibly calling the method wrong?
You need to call the method like so:
vncSort.sorts(carList, 2, vnc);
Also, it seems like you're confusing an array with an ArrayList. An Array of Car would be Car[]. An ArrayList<Car> is a List which accepts and produces Car types. The reason it's called ArrayList is because it's backed internally by an array.
I am trying to access a variable that is stores as part of an object that is in an array. However that array is in an arraylist. How can access that variable?
To make it clear, I have a car object that has speed. I placed 4 cars in an array. And that array is duplicated and put in an arraylist.
public int getSpeedOfCarA (int index) {//used to access the variable speed in an array
return garage [index].getSpeed ();
}
Now I was trying this but got stuck.
public int getSpeedOfCarB(int n){
carSpeeds.get(...); //not sure what to use here.
}
To access things inside of other things, simply chain the access syntax together. For the example of getting a field inside an object inside an array inside a List, you would simply use
list.get(pos)[arrayPos].fieldName
You may be misunderstanding how ArrayList works however: When working with it, you never see the array, and in fact as far as syntax is concerned it doesn't matter whether it's implemented as an Array or as a LinkedList or whatever else. If so, you need not use any array operator, as the get method will do that for you:
list.get(pos).fieldName
I prefer to use an Iterator to access the car object in the list.
ArrayList<Car> list = new ArrayList<Car>();
Iterator i = list.iterator();
while(i.hasNext()){
Car car = i.next();
}
Use,
for(Car[] carArrays : listOfCarArrays) {
for (Car car : carArrays) {
//do something with car like car.getSpeed();
}
}
I've got a function to create syllables for words.
I use it like this: syllables(word1field); - creates List with syllables: aa,bb,cc
and syllables(word2field); - creates List with syllables: dd,ee,ff
And in the result I get dd,ee,ff, but I need aa,bb,cc,dd,ee,ff.
Is there possibility to append second list to first?
You get dd,ee,ff because when you call the same method again, it overrides the first ArrayList that is created.
The best thing you could do, that I can think of, is to make your ArrayList global because currently you just keep getting rid of the previous values and create a new ArrayList with the new values you give it. Try doing something like:
public class MyClass {
private List<String> myArray;
public MyClass() {
myArray = new ArrayList<String>();
}
public void syllables(wordfield) {
// do whatever you need to with wordfield
myArray.add(syllable);
}
I don't know how you've got everything laid out but this is the best solution I can think of.