I have created a list of items from a CSV file, but am not sure how to access this list in another class. I have created the instance of the list class in the new class, but have not been able to find a way to access the list.
public class ListClass {
public static void main(String[] args) throws IOException {
CSVReader csvReader = new CSVReader();
List list = csvReader.Read("csvFile.csv");
}
}
I have been able to print the list, and so I know that it's definitely working, but I'm just not sure how I'd access it in another class. The new class is currently empty, aside from the following;
ListClass listClass = new ListClass();
You should store the list as a private instance variable in your ListClass and create a getter for it:
public class ListClass {
private List list = null;
public static void main(String[] args) {
try {
new ListClass();
} catch(IOException ioEx){
// error handling
}
}
public ListClass() throws IOException {
CSVReader csvReader = new CSVReader();
list = csvReader.Read("csvFile.csv");
}
public List getList(){
return list;
}
}
Then you can access it from your other class:
try {
ListClass listClass = new ListClass();
List list = listClass.getList();
} catch(IOException ioEx){
// error handling
}
You need to make the list accessible to other classes by doing one of the following:
Delcare the list as a class level variable and make it public
class ListClass {
public List csvList;
...
}
Declare the list as a private class variable and have an accessor
class ListClass {
private List csvList;
public List getCsvList() {
return this.csvList;
}
...
}
There are a lot of other ways to access a class variable. The second one is a very common way of doing it.
1 )Add your list as a Field of ListClass and put your initialization inside the constructor.
public class ListClass {
public List list;
ListClass(){
try{
CSVReader csvReader = new CSVReader();
list = csvReader.Read("csvFile.csv");
}catch(IOException e){
//handle the exception
}
}
}
2) create an object of ListClass in OtherClass.
public class OtherClass{
public static void main(String[] args){
ListClass listClass = new ListClass();
List newList = listClass.list;// your list
}
}
Related
I have a problem with Java's Generic System.
In my program is a wrapper for lists, that should have a method to return it's inner list:
public class Wrapper<T, S extends List<T>> {
private S list;
public Wrapper(S list) {
this.list = list;
}
public S get() {
return list;
}
}
Then there is a Context that holds a Map with different Wrappers and a method that returns the list of the wrapper associated with the id:
public class Context {
private Map<String, Wrapper> map;
public Wrappers() {
map.put("a", new Wrapper(ArrayList<String>());
map.put("b", new Wrapper(LinkedList<Integer>());
}
public <T, S extends List<T>> S getList(String id) {
return map.get(id).get();
}
}
Now when I call getList() I want to have a compiler warning or at least a way to realise an error before a ClassCastException gets thrown.
public class Receiver {
public doSomething() {
Context c = new Context();
c.createWrappers();
// Ok
ArrayList<String> list1 = c.getList("a");
LinkedList<Integer> list2 = c.getList("b");
// Compiler error or some way do check in getList().
ArrayList<Integer> list3 = c.getList("a");
LinkedList<String> list4 = c.getList("b");
}
}
I've actually tried a lot of things like changing the Wrapper definition to:
public class Wrapper<T, S extends List>
But when I want to implement the get() function I run into a problem I can either define the function like this:
public List<T> get() {
return list;
}
or like this
public S get() {
return list;
}
In the first example it would still be possible to do this.
public doSomething() {
//...
LinkedList<String> list = c.getList("a");
}
and in the second example it would be possible to do this.
public doSomething() {
//...
ArrayList<Integer> list = c.getList("a");
}
Is there any way to define the get method in a way like this?
public S<T> get() {
return list;
}
It seems to me like there is no way to check both the type of the list and the type of the elements at the same time.
The compiler has no way of knowing what return type is associated with the particular string you passed (strings cannot be made type-safe).
However, you could replace strings with type-safe marker objects:
class ListId<T> {
public ListId(string name) { ... }
public static final ListId<ArrayList<String>> A = new ListId<>("a");
public static final ListId<LinkedList<Integer>> B = new ListId<>("b");
}
public T getList<T>(ListId<T> id)
I have such problem.
I want to get arraylists from Java classes and join to one main arraylist in fragment.
public ArrayList<Coin getAll() {
ArrayList<Coin alllist = new ArrayList<();
alllist.addAll( I want this from java class getArraylist1());
alllist.addAll( I want this from another java class getArraylist2());
return alllist;
}
getArraylist1() and getArraylist2() this are array list in other classes. And I want to make on main arraylist.
Arraylists are not static
public ArrayList<Coin> getArraylist1()
{
ArrayList<Coin> coins = new ArrayList<>();
Coin coadd = new Coin();
coadd.setCoinid("RC2022");
coadd.setCoinimages(R.drawable.fivrubl1798);
coadd.setDenom("5");
coins.add(coadd);
return coins;
}
You can create objects of other classes and call get methods, e.g.:
public ArrayList getAll(){
ArrayList<Coin> list = new ArrayList<>();
YourClass yourObject = new YourClass();
AnotherClass anotherObject = new AnotherClass();
list.addAll(yourObject.getArraylist1());
list.addAll(anotherObject.getArraylist2());
return list;
}
If getArraylist1 and getArraylist2 methods are static then you don't need to create objects, e.g.:
public ArrayList getAll(){
ArrayList<Coin> list = new ArrayList<>();
list.addAll(YourClass.getArraylist1());
list.addAll(AnotherClass.getArraylist2());
return list;
}
public class Common implements Serializable{
private static HashMap<Integer,List<LevelList>> levelListMap = new HashMap<>();
public static Map<Integer, List<LevelList>> getLevelListMap(Context context) {
File file = new File(context.getDir("data", MODE_PRIVATE), "map");
ObjectInputStream inputStream = null;
try {
inputStream = new ObjectInputStream(new FileInputStream(file));
levelListMap = (HashMap<Integer, List<LevelList>>) inputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return levelListMap;
} ...
}
I am unable to serialize hashmap.I keep getting java.io.NotSerializableException for
levelListMap = (HashMap<Integer, List<LevelList>>) inputStream.readObject();
public class LevelList implements Serializable{
public int id;
public String title;
public String imgurl;
public String songurl;
public String songtext;
boolean isFavourite;
public void release() {
}
public void setFavourite(boolean favourite) {
isFavourite = favourite;
}
public boolean isFavourite(){
return isFavourite;
}
}
HashMap is serializable, but the keys and values must also be serializable. Make sure that all keys and values are serializable, and that their fields are also serializable (excluding transient and static members).
Edit:
HashMap<Integer,List<LevelList>>, is your List implementation serializable?
Check this link How to serialize a list in Java. Standard implementation of List, i.e. ArrayList, LinkedList, etc. are serializable.
If you declare your List as one of the List subtypes such as ArrayList<LevelList> levelList = new ArrayList<LevelList>(); then it should be serializable out of the box. Otherwise you will need to cast in a safe way, such as setting the List implementation with <T extends List<Foo> & Serializable> setFooList(T list) as suggested by Theodore Murdock in that answer thread.
I have an IMAP whose key is a String and value is a derivative of ArrayList. I need to run EntryProcessor on a key of this map. Also note that Employee is a POJO which implements Serializable interface.
When I executed the code given below, the code prints "Why so !" and I got ClassCastException which mentioned that java.util.ArrayList cannot be cast to Employees in the process() method of ListValueEntryProcessor given below.
Q1. I learnt that I need to add custom serializer for my type (Employees) so that it could be serialized as Employees object and not as ArrayList object. I would like to know why is it mandatory to add a "custom serializer" for a built-in type like an ArrayList whose items are also marked Serializable ?
public class Employees extends ArrayList implements Serializable
{
private static final long serialVersionUID = 1L;
/**
Constructs a new employees object
*/
public Employees()
{
super();
}
}
HazelcastInstance hazelcastInstance = HazelcastHelper.getHazelcastInstance();
IMap<String, Employees> empMap = hazelcastInstance.getMap("employeesMap");
Employees empList = new Employees();
Employee employee = new Employee();
empList.add(employee);
empMap.put("companyId", employees);
empMap.executeOnKey("companyId", new IncSalaryEntryProcessor());
public static class ListValueEntryProcessor extends AbstractEntryProcessor<String, Employees>
{
private static final long serialVersionUID = 1L;
#Override
public Object process(Entry<String, Employees> arg0)
{
if(! (arg0.getValue() instanceof Employees))
{
System.out.println("Why so !");
}
// ClassCastException thrown here.
Employees empList = arg0.getValue();
return true;
}
}
This is a bug on our side. I created a bugreport:
https://github.com/hazelcast/hazelcast/issues/6455
The following code should resolve your problem for the time being:
public class Main {
public static void main(String[] args){
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
IMap<String,Employees> map = hz.getMap("foo");
map.put("1", new Employees());
Employees employees = map.get("1");
System.out.println(employees);
}
static class Employees extends ArrayList implements DataSerializable {
#Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(size());
for(Object item: this){
out.writeObject(item);
}
}
#Override
public void readData(ObjectDataInput in) throws IOException {
int size = in.readInt();
for(int k=0;k<size;k++){
add(in.readObject());
}
}
}
}
I'm using the restlet library and Jackson to send JSON data, and I cannot get the following to return a json object for a List, I get null out of it and no errors:
public class Info extends ServerResource {
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception {
Server server = new Server(Protocol.HTTP,8080,Info.class);
System.out.println("Starting: " + args[0]);
server.start();
System.out.println("Start returned: " + args[1]);
ObjectMapper mapper = new ObjectMapper();
List<String> user = new ArrayList<String>();
user.add("SDFE");
user.add("XXYY");
Object o = "user";
mapper.writeValue(new File("/tmp/user.json"), o);
}
/*#Get("json")
public String isAwake()
{
System.out.println("Getting true");
return "true";
}*/
#Get("json")
// public List los()
//public String[] los()
public String los()
{
ArrayList l = new ArrayList<String>();
String[] sl = new String[2];
sl[0] = "FDSSE";
sl[1] = "ODSEF";
l.add("ESDF");
l.add("JJKE");
//return l;
return sl.toString();
// return sl[0];
}
As you might be able to tell from the comments, I've done this a number of ways, with List, Object, and String[] being returned. I cast the List to Object for that part.
If I return a plain String, it gets encoded and sent. I cannot make the List send back a JSON array
I had a similar issue. If I understood everything correctly, Jackson needs a class to serialize, and had trouble when handed a list. So I fixed this by creating a class for the list, basically wrapping it:
public class MyObject {
//object details with setters and getters
}
and then a second class that contained a list of those:
public class MyObjectList {
private List<MyObject> myObjectList;
//and appropriate setter and getter
}
Then my URL call was:
#GET
public MyObjectList getMyObject() {
//method defined
}
Hope that helps! If there's a better way I'll be curious to see it myself!