Java abstract Issue [duplicate] - java

This question already has answers here:
"Instantiating" a List in Java? [duplicate]
(6 answers)
How to declare an ArrayList with values? [duplicate]
(6 answers)
Closed 4 days ago.
Hi i want to fix this error
java: java.util.List is abstract; cannot be instantiated.
I tryied to add extends to second file but this dont work
idk cause this error
i m new in java programming and i need help
I added code below
Thx for help
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
System.out.println("What you want to do");
System.out.println("1.EDIT BOOKS");
System.out.println("2.BORROWING AND RETURNING BOOKS");
System.out.println("3.SEARCH FOR BOOK");
var x =scanner.nextInt();
switch (x) {
case 1:
System.out.println("1.ADD BOOK");
System.out.println("2.DELETE BOOK");
var z =scanner.nextInt();
switch (z){
case 1:
System.out.println("Enter book name");
String name=scanner.nextLine();
System.out.println("Enter username");
String user=scanner.nextLine();
List list= new List(user,name);
}
;break;
case 2: System.out.println("2");break;
case 3: System.out.println("2");break;
}
}
}
import java.util.HashMap;
public class LIST {
String bookname;
String user;
void newuser(String user,String bookname){
this.user=user;
this.bookname=bookname;
}
HashMap<String,String> Books =new HashMap<String,String>();
}

List.of
To instantiate an unmodifiable List using literals syntax, use List.of methods.
List< String > list = List.of( user , name ) ;
As commented by Dave Newton, you cannot actually instantiate an interface such as List. Under the covers, the .of method has a default implementation. That implementation instantiates an object of some unspecified concrete class that implements the List interface.
Adding to a list
I am guessing the purpose of your app is to collect info about multiple people and their favorite or borrowed book. If so you should collect those pieces of data as fields on an object of a custom class.
A record is a brief way to declare a custom class whose main purpose is to communicate data transparently and immutably.
record BookUser ( String user , String book ) {}
Make a list to collect multiple objects. An ArrayList is a modifiable List.
List< BookUser > bookUsers = new ArrayList<>() ;
Instantiate objects, and collect.
BookUser bu = new BookUser( user , name ) ;
bookUsers.add( bu ) ;

Related

Using foreach loop with methods in another class (Java) [duplicate]

This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 6 years ago.
I have a program that creates a couple objects and adds each one to an ArrayList, then is supposed to loop over each object in the ArrayList and use a getter from another class within the project to display information on each object. I can't get the objects in my foreach loop to use any of the methods in my other class. Here is my main, including the trouble loop at the bottom:
import java.util.ArrayList;
public class ITECCourseManager {
public static void main(String[] args) {
ArrayList ITECCourse = new ArrayList();
ITECCourse infotech = new ITECCourse("Info Tech Concepts", 1100, 5, "T3050");
infotech.addStudent("Max");
infotech.addStudent("Nancy");
infotech.addStudent("Orson");
ITECCourse.add(infotech);
ITECCourse java = new ITECCourse("Java Programming", 2545, 3, "T3010");
java.addStudent("Alyssa");
java.addStudent("Hillary");
ITECCourse.add(java);
for (Object course : ITECCourse) {
System.out.println("Name: " + course.getName());
}
}
}
And here is the other class in my project with the method I need to use:
public class ITECCourse {
public String name;
public int code;
public ArrayList<String> students;
public int maxStudents;
public String room;
ITECCourse(String courseName, int courseCode, int courseMaxStudents, String roomNum) {
name = courseName;
code = courseCode;
maxStudents = courseMaxStudents;
students = new ArrayList<String>();
room = roomNum;
}
public String getName() {
return name;
}
If I replace course.getName() with java.getName(), the code works. I'm confused why I can't use a foreach loop across the ArrayList to use the getter for each object, when I am able to call the object and use the method directly from the same place in the code.
Edit: Thank you for the answers, simple mistake only had to make two/three changes: declare ArrayList<ITECCourse> at the beginning, change Object in for loop to ITECCourse, and of course change my arraylist from ITECCourse to ITECCourseList so there isn't confusion with my ITECCourse class.
The call to course.getName() doesn't work because you've defined course as an Object in your loop and Object doesn't have the method getName(). If you add a type parameter to your ArrayList declaration such as ArrayList<ITECCourse>, then you can iterate over the list of ITECCourse instances rather than Object.
On a side note, naming your variable ITECCourse will just lead to confusion because it's the same as your class. Might be better to name your variable something like itecCourseList.

How to use for each to iterate object of a class [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
I am wondering if I can use for each loop to iterate through the object of a class. for instance, I created an object honda of type car. I append all the state of the car such as model, price, color, etc. to it. I want to print all the instance of the car. I don't want to use the print statement to print each instance . what is the best way to do it? Thanks.
Below is my java code
package classandobjects;
public class MainClass {
public static void main(String[] args) {
Classes friend1 = new Classes();
friend1.name="yusuf";
friend1.age=27;
friend1.country="Nigeria";
friend1.department="EE";
friend1.gender="male";
Classes friend2 = new Classes();
friend1.name="mathew";
friend1.age=30;
friend1.country="Nigeria";
friend1.department="EE";
friend1.gender="male";
FavPlayers player = new FavPlayers();
player.pname="J.Terry";
player.position="C.Back";
player.gaols=38;
player.awards="25-awards";
FavPlayers player1 = new FavPlayers();
player1.pname="F.Lampard";
player.position="Midfield";
player.gaols=50;
player.awards="10-awards";
Car model = new Car();
model.modelName="Honda Civic";
model.color="Ash-color";
model.Doors="4-doors";
model.price=900000;
System.out.println("below is my friend information");
System.out.println(friend1.name);
System.out.println(friend1.age);
}
}
​
You had better override a toString method in the Car class and simply print it like:
System.out.println(model);
Indeed, you needn't print each instance variable separately. Your toString may have the following view:
public #Override String toString() {
return modelName + " [" + color + ... + "]"; // also consider StringBuilder
}
If you came from languages where an object is an associative array (e.g. JavaScript) and asked how to print an instance using a foreach loop in Java, then the answer is that Java doesn't allow it (it is possible by reflection though) and you cannot iterate over object variables through a foreach.
I don't want to use the print statement to print each instance
Well, you're going to have to build up a string and print it somewhere.
what is the best way to do it?
If I understand correctly, you want to print an object?
Then implement a toString() method.
public class Classes {
// other code
public String toString() {
// change how you want
return this.name + ", " + this.age;
}
}
Then you can do
System.out.println(friend1);
If you want to print a list of objects, then you need a list to loop over. You could use reflection to get a list of object fields and values, but that seems unnecessary.

Saving an object that contains a list of objects to the disk

The title may be a little be confusing or even missleading but im trying to save to disk an object that as a property contains a list of objects (ArrayList).
The thing is this object wont be able to do anything without the list.
I have tried serialization of both the object and the list. When i tried serializing the object alone there was nothing in it, the list was empty. When i tried serializing the list i could access the list, change it but at the cost of many thrown exceptions.
public class AdressBook implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6399534374362987383L;
static Reader reader = new KeyboardReader();
static ArrayList<Contact> AdressBook = new ArrayList<Contact>();
public AdressBook(){
}
public static void AddContact(){
AdressBook.add(new Contact());
}
public static void EditContact(){
System.out.println("Which contact you desire to edit?");
Libreta.Display();
System.out.println("Type in the number of the contact.");
int i = (reader.readint() - 1);
System.out.println("Choose the change 1.Name 2.Last Name 3.Nickname 4.Phone number 5.Emails");
int j = reader.readint();
switch(j){
case 1: AdressBook.get(i).setName();
break;
case 2: AdressBook.get(i).setLastName();
break;
case 3: AdressBook.get(i).setNick();
break;
case 4: AdressBook.get(i).AddPhoneNumber();
break;
case 5: AdressBook.get(i).AddEmail();
break;
default : System.out.println("Not a valid option");
}
I have to be able to edit the list of the object and being able to somehow save it again. I have been trying many ways but im lacking in knowledge or it just doesnt work for me.
Your address book variable should not be declared static, as static variables are not serialized. Make it an instance (non-static) variable like this:
public class AddressBook implements Serializable {
...
ArrayList<Contact> contacts = new ArrayList<Contact>();
...
}
I think your problem is that your ArrayList is a static field (sometimes called a class field) and serialization take place in an object instance not in class.
So you should replace your static field, and static methods too, for instance equivalents.
(Now, just a comment: you should try using java naming conventions - using lower initials for field and method names - it much easy for java coders understand you... ;-)

How to sort Java ArrayList [duplicate]

This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 9 years ago.
Ive got a file called HighScores.txt which contains player names and number of points:
name1 2
name2 5
name3 1
name4 23
name5 51
And heres my code that reads the contents of this file, splitting each line and appending it to the ArrayList highScores:
public class fileHandling {
static ArrayList highScores = new ArrayList();
public static void readFile(String[] args) throws Exception {
File file = new File(fileHandling.class.getClassLoader()
.getResource("HighScores.txt").getPath());
Scanner read = new Scanner(file);
while (read.hasNextLine()) {
String line = read.nextLine();
String[] result = line.split("\\s+");
highScores.add(Arrays.toString(result));
System.out.println(highScores);
}
}
}
How do i then sort this ArrayList by the number of points each player has?
i.e. so the new array list will be:
[[name5, 51], [name4, 23], [name2, 5], [name1, 2], [name3, 1]]
You can create a separate object for every line in your file and then use Comparable or Comparator interface to sort these objects. Then use Collections.sort(arrayList,sorter).
You can find a good tutorial here to sort user defined objects.
The class for the same can be
public class Player{
private String name;
private Integer score;
//getters and setters here
}
Then create a sorter for Player objects as follows.
public class ScoreSort implements Comparator<Player>{
public int compareTo(Player first, Player second){
// implement sorting logic here
}
}
Then use Collections.sort(playerList, new ScoreSort()). You can find a good tutorial at following link
http://www.thejavageek.com/2013/06/17/sorting-user-defined-objects-part-2/
Create a class with 2 member variable name and score. Create a new instance of class for each entry in file and store it in ArrayList.
Now this class should also implement Comparable interface which compares based on score. Now use Collections.sort

Is it possible to add different types to a single arraylist in Java?

I need to create an ArrayList (well it doesn't have to be an ArrayList but that's what I'm attempting so far) to hold student ids, marks, and course names.
I have something like this so far:
import java.util.*;
public class MarksHandling {
static Scanner keybrd = new Scanner(System.in);
public static void main (String[]args){
ArrayList<String> studentsCourses= new ArrayList<String>();
ArrayList marks= new ArrayList();
while (keybrd.next()!="-1"|| keybrd.nextInt()!=-1){
System.out.println("Please Type Your ID Number (-1 to quit)\n");
studentsCourses.add(keybrd.next());
System.out.println("Please Type Your Course Name (-1 to quit)\n");
studentsCourses.add(keybrd.next());
System.out.println("Please Type Your Mark (-1 to quit)\n");
marks.add(keybrd.nextInt());
}
System.out.println("Done");
}
}
(Mind the indentation; it tends to be messed up when I paste in from my IDE)
I understand that I could just enter all of them as strings and it would be find; but in the end I need to find which student has the highest grade and in which course...
So I thought of trying two different arrays (One for Strings and one for Int)
but that caused issues with my sentinel (Which I am currently trying to fix..)
Is there a way to accept both "int" and "String" types into the same arrayList and access them as such?
Better way to do this in a OO language is to create a Student class with id, marks, and course names as member variables of this class, and to use
ArrayList<Student> studentsCourses= new ArrayList<Student>();

Categories