How do you pass an ArrayList into the constructor? - arraylist

import java.util.ArrayList;
public class Finance {
ArrayList<String> title = new ArrayList<String>();
ArrayList<Double> moneySpent = new ArrayList<Double>();
Scanner input = new Scanner(System.in);
public Finance(ArrayList<String> title, ArrayList<Double> moneySpent){
this.title = title;
this.moneySpent = moneySpent;
System.out.println(title);
System.out.println(moneySpent);
}
public static void main(String[] args){
Finance entertainment = new Finance(title.add("Movies"), moneySpent.add(1));
}
When I run the code this, I found 2 errors:
File: D:\Java Programs\Finance.java [line: 19] Error: Cannot make a
static reference to the non-static field title
File: D:\Java
Programs\Finance.java [line: 19] Error: Cannot make a static
reference to the non-static field moneySpent

Although your focus is in creating an instance Finance there are few concepts I'd like to invite you to explore.
To start and to answer your question, the Finance's contructor signature defines the contract for a Finance oject to become an instance.
It expects two arguments, each of which are of ArrayList type.
To create an instance of Finance you have to create two arrays, one made of Strings and the other made of Doubles, on this thread you have many ideas on how to initialise arrays.
An example could be,
new Finance(new ArrayList<>(List.of("Movies")), new ArrayList<>(List.of(1.0)));
Next, I'd like to drag your awareness on this expression in your code:
title.add("Movies")
title is what you want initialised inside your constructor and altough is not a bad idea to have it initialised as an empty ArrayList as you did, it's pointless to add an element to it and then pass it to your constructor for it to change the same instance object.
Next, I'd like to drag your awareness on the types you are using:
In my personal opinion I would use java's List interface when declaring variables, use a plural to name any collection of objects, and in your case, use ArrayList as the List interface implementing class. For example,
List<String> titles;
// and
List<Double> expenses;
Same on the constructor:
public Finance(List<String> titles, List<Double> expenses) {
//...init variables here
}
Note that I renamed moneySpent to expenses. I did this because a money spent on multiple moments it's more likely to be expenses and moneySpent would be the amount spent on a single moment.
Applying Single Resposibility I would refactor the creation of a Finance instance onto a separete (static, why static?) method.
public class Finance {
List<String> titles;
List<Double> expenses;
Scanner input = new Scanner(System.in);
public Finance(List<String> titles, List<Double> expenses) {
this.titles = titles;
this.expenses = expenses;
System.out.println(this.titles);
System.out.println(this.expenses);
}
public static void main(String[] args) {
Finance entertainment = createFinance();
}
private static Finance createFinance() {
return new Finance(
new ArrayList<>(List.of("Movies")),
new ArrayList<>(List.of(1.0)));
}
}
Lastly, Consider driving your implementation guided by tests. I can recommend:
TDD by example, GOOS and Jason Gorman's TDD book

Related

Kotlin object, an implementation vs instance

In Objects in Kotlin: Create safe singletons in one line of code (KAD 27) Antonio Leiva states:
In fact, an object is just a data type with a single implementation.
I would expect to see the term instance rather than implementation used here. Is there some nuance that I am missing?
Sure it does have a single instance after all, but I believe what they meant to say is that whatever you write in an object is final and you can not override it. Even if you make it open(for argument purpose), you can not make an anonymous object out of it since the anonymous class can't be used on a SingleTon instance.
So " data type with a single implementation" means, whatever you write is the final implementation. An instance is, after all, a result of some implementation.
For reference, I am adding a decompiled code of object declaration.
public final class Test {
#NotNull
private static final String testMember = "Test";
public static final Test INSTANCE;
#NotNull
public final String getTestMember() {
return testMember;
}
private Test() {
}
static {
Test var0 = new Test();
INSTANCE = var0;
testMember = "Test";
}
}

Convert ArrayList to Observable List for JavaFX program?

I am a semi-beginner Java programmer, learning Java FX from a variety of sources. In my program, I would like to create a ComboBox, and populate the choices with the toString() output of a series of objects from an ArrayList. Here, pizza toppings are defined as an object. They are created and stored in a PizzaMgr object, basically a glorified wrapper for an ArrayList:
public class Topping{
private String name;
public Topping(String a){
this.name=a;
}
public String toString(){
return this.name;
}
}
//=================================================
import java.util.ArrayList;
public class PizzaMgr{
private ArrayList<Topping> OrderedToppings;
public PizzaMgr(){
OrderedToppings = new ArrayList<Topping>();
OrderedToppings.add(new Topping("Pepperoni"));
OrderedToppings.add(new Topping("Mushrooms"));
OrderedToppings.add(new Topping("Onions"));
}
public ArrayList<Topping> getList(){
return OrderedToppings;
}
}
So far, so good. But the hitch I hit is when I want a ComboBox to list all of those items in the PizzaMgr's ArrayList. Ideally, I'd like to use this ComboBox constructor:
ComboBox<T>(ObservableList<T> items)
The problem? How to extract all the ArrayList items into an Observable List? I've been reading up on Arraylists, Observable Lists, interfaces in general, but I can't figure out how to get this to work. I've read that an ArrayList is a Collection, and Observable List can be an interface to a Collection, so I thought I was home free. However, when I try to implement the ComboBox constructor:
import javafx.scene.control.*;
public class Menu{
public static void main(String[] args){
PizzaMgr m = new PizzaMgr();
ComboBox<Topping> topMenu = new ComboBox<Topping>(m.getList());
}
}
I get the compiler error:
Menu.java:18: error: incompatible types: ArrayList<Topping> cannot be converted to ObservableList<Topping>
ComboBox<Topping> topMenu = new ComboBox<Topping>(m.getList());
^
So obviously my ArrayList isn't seen as an Observable List.
What stumps me is: How can I present my ArrayList to the ComboBox constructor, making it seem like an Observable List? Is it a syntax slight-of-hand? Or do I have to convert the ArrayList into another data structure in advance?
Many thanks,
-RAO
ObservableList is a sub interface (specialized version of) List. (ObservableList adds functionality for observing changes to the list.) ArrayList is a particular implementation of List, but is not an implementation of ObservableList. Hence you can pass an ArrayList anywhere a List is expected, but you cannot pass an ArrayList if an ObservableList is expected.
As something of an aside, note it's not really recommended to expose the implementation type, but you should really just expose the interface type:
import java.util.List;
import java.util.ArrayList;
public class PizzaMgr{
private List<Topping> orderedToppings;
public PizzaMgr(){
orderedToppings = new ArrayList<Topping>();
orderedToppings.add(new Topping("Pepperoni"));
orderedToppings.add(new Topping("Mushrooms"));
orderedToppings.add(new Topping("Onions"));
}
public List<Topping> getList(){
return orderedToppings;
}
}
To create an ObservableList from a regular List, you can use
ComboBox<Topping> topMenu
= new ComboBox<Topping>(FXCollections.observableList(m.getList()));
which creates a new ObservableList that "wraps" the array list you provide. I.e. calling get(index) or add(item) on the observable list simply delegates to the list you provide.
You could also do
ComboBox<Topping> topMenu
= new ComboBox<Topping>(FXCollections.observableArrayList(m.getList()));
which would create a new observable list and copy all the elements from the list you provide into it. So subsequently manipulating one list would not change the other.
To create an observableList you need to, first of all, have a predefined list eg an arrayList. Pass the list to an instance of observableList as below...
//Assuming you had this for a list
List<String> list = new ArrayList<String>();
//Pass it over in this manner
ObservableList<String> observableList = FXCollections.observableList(list);
//Then add a listener
observableList.addListener (new ListChangeListener() {
//override the method here
}
Hope it will help...
ArrayList<Site> sites = new ArrayList < Site > ();
sites.add(new Site("Google", "http://www.google.com"));
ObservableList<Site> siteList = FXCollections.observableArrayList(sites);
final ComboBox comboBox = new ComboBox(siteList);
Button btn = new Button();
btn.setText("Read comboBox");
btn.setOnAction(new EventHandler < ActionEvent > () {
#Override
public void handle(ActionEvent event) {
label.setText("selected: " + comboBox.getValue());
Site site = (Site) comboBox.getSelectionModel().getSelectedItem();
System.out.println(site.name);
}
});

Jackson, how to expose fields when serializing a class which extend a collection?

I have a class that we use for paginated results, as follows:
public class PaginatedList<T> extends LinkedList<T> {
private int offset;
private int count;
private int totalResultCount;
//...
}
and I'd like Jackson to serialize it like this:
{
"results":[1,2,3],
"offset":0,
"count":3,
"totalResultCount":15
}
(where the parent list contains the three integer values 1,2 and 3.)
In my first attempt I discovered that Jackson effectively ignores any properties on classes which are assignable to a Collection class. In hindsight, this makes sense, and so I'm now in search of a workaround. A search of SO resulted in two similar questions:
jackson-serialization-includes-subclasss-fields
jaxb-how-to-serialize-fields-in-a-subclass-of-a-collection
However, both of these resulted in the suggestion to switch from inheritance to composition.
I am specifically looking for a solution that allows the class to extend a collection. This 'PaginatedList' class is part of the common core of the enterprise, and extends Collection so that it can be used (and introspected) as a collection throughout the code. Changing to composition isn't an option. That being said, I am free to annotate and otherwise change this class to support serialization as I described above.
So, from what I can tell, there's two parts I'm missing (what I'm looking for in an answer):
How to get Jackson to 'see' the added properties?
How to get Jackson to label the collection's content as a 'results' property in the JSON output?
(PS: I'm only concerned with serialization.)
Ashley Frieze pointed this out in a comment, and deserves the credit for this answer.
I solved this by creating a JsonSerializer instance as follows:
public class PaginatedListSerializer extends JsonSerializer<PaginatedList> {
#Override
public Class<PaginatedList> handledType() {
return PaginatedList.class;
}
#Override
public void serialize(PaginatedList value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeArrayFieldStart("results");
for (Object entry : value) {
jgen.writeObject(entry);
}
jgen.writeEndArray();
jgen.writeNumberField("offset", value.offset);
jgen.writeNumberField("count", value.count);
jgen.writeNumberField("totalResultCount", value.totalResultCount);
jgen.writeEndObject();
}
}
and, of course, register it as a module:
SimpleModule testModule = new SimpleModule("PaginatedListSerializerModule", new Version(1, 0, 0, null, null, null));
testModule.addSerializer(new PaginatedListSerializer());
mapper.registerModule(testModule);

Changing Class Variables in runtime?

Let me give an idea of what I wish to do: I have a structure or class called student, which contains variables like
int roll_no
and
int reg_no
If the user wishes to add a new variable like char name at run time how can it be done?
Based on the word "Structure" and the variable declarations, I'm going to guess this question is about some flavor of C. How exactly to do this will depend on the language, but as a general rule, if the language is compiled (e.g. C/C++, Java), this is not possible. If the language is interpreted (e.g. Python), this might sort of be possible, like this:
class MyObj:
message = "Hi there"
a = MyObj() # Creating a new instance variable
a.name = "Bill" # Adding a new attribute
Here we've added the name attribute to the a object only, and not the entire class. I'm not sure how you're go about that for the whole class.
But really, the answer to your question is "Don't". You should think about your program and the objects you're using enough to know what fields you will and won't need. If you'll want to have a name field at some point in your program, put it in the class declaration. If you don't want it to have a value on object creation, use a sensible default like null.
Edit
Based on your comments, there are a couple of ways to approach this. I'm still not entirely clear on what you want, but I think one of these cases should cover it. Of the languages I know, Python is the most flexible at runtime:
Python
In Python, a class is just another kind of object. Class variables (check out this question too) belong to the class itself, and are inherited by any instances you create:
class MyObj:
a = 2 # A class variable
b = "a string" # Another one
ObjInstance = MyObj() # Creating an instance of this class
print ObjInstance.a # Output: "2"
ObjInstance.a = 3 # You can access and change the value of class variables *for this instance*
print MyObj.a, ObjInstance.a # Outputs "2 3". We've changed the value of a for the instance
MyObj.c = (3,4) # You can add a new class variable at runtime
# Any instance objects inherit the new variable, whether they already exist or not.
print MyObj.c, ObjInstance.c # Outputs "(3, 4) (3, 4)"
You can use this to add attributes to every instance of your class, but they will all have the same value until you change them. If you want to add an attribute to just one instance, you can do this:
ObjInstance.d = "I belong to ObjInstance!"
print ObjInstance.d # Output: "I belong to ObjInstance!"
print MyObj.d # Throws "AttributeError: class MyObj has no attribute 'd'"
One drawback to using Python is that it can be kinda slow. If you want to use a compiled language it will be slightly more complicated, and it will be harder to get the same functionality that I mentioned above. However, I think it's doable. Here's how I would do it in Java. The implementation in C/C++ will be somewhat different.
Java
Java's class attributes (and methods) are called (and declared) static:
class MyObj {
public static int a = 2;
public static String b = "a string";
}
static variables are normally accessed through the class name, as in Python. You can get at them through an instance, but I believe that generates a warning:
System.out.println(MyObj.a); //Outputs "2"
MyObj ObjInst = new MyObj();
System.out.println(ObjInst.a); //Outputs "2" with a warning. Probably.
You can't add attributes to a Java object at runtime:
ObjInst.c = "This will break"; // Throws some exception or other
However, you can have a HashMap attribute, static or not, which you can add entries to at runtime that act like attributes. (This is exactly what Python does, behind the scenes.) For example:
class MyObj {
private HashMap<String, Object> att = new HashMap<String, Object>();
public void setAttribute(String name, Object value) {
att.put(name, value);
}
public Object getAttribute(String name) {
return att.get(name);
}
}
And then you can do things like:
ObjInst.setAttribute("name", "Joe");
System.out.println(ObjInst.getAttribute("name"));
Notice that I did not declare att static above, so in this case each instance of the MyObj class has this attribute, but the class itself does not. If I had declared it static, the class itself would have one copy of this hash. If you want to get really fancy, you can combine the two cases:
class MyObj {
private static HashMap<String, Object> classAtt = new HashMap<String, Object>();
private HashMap<String, Object> instAtt = new HashMap<String, Object>();
public static void setClassAttribute(String name, Object value) {
classAtt.put(name, value);
}
public void setInstAttribute(String name, Object value) {
instAtt.put(name, value);
}
public Object getAttribute(String name) {
// Check if this instance has the attribute first
if (this.instAtt.containsKey(name) {
return instAtt.get(name);
}
// Get the class value if not
else {
return classAtt.get(name);
}
}
}
There are a few details I've left out, like handling the case of the HashMaps not having the value you're asking for, but you can figure out what to do there. As one last note, you can do in Python exactly what I did here in Java with a dict, and that might be a good idea if the attribute names will be strings. You can add an attribute as a string in Python but it's kind of hard; look at the documentation on reflection for more info.
Good luck!

What is the real significance(use) of polymorphism

I am new to OOP. Though I understand what polymorphism is, but I can't get the real use of it. I can have functions with different name. Why should I try to implement polymorphism in my application.
Classic answer: Imagine a base class Shape. It exposes a GetArea method. Imagine a Square class and a Rectangle class, and a Circle class. Instead of creating separate GetSquareArea, GetRectangleArea and GetCircleArea methods, you get to implement just one method in each of the derived classes. You don't have to know which exact subclass of Shape you use, you just call GetArea and you get your result, independent of which concrete type is it.
Have a look at this code:
#include <iostream>
using namespace std;
class Shape
{
public:
virtual float GetArea() = 0;
};
class Rectangle : public Shape
{
public:
Rectangle(float a) { this->a = a; }
float GetArea() { return a * a; }
private:
float a;
};
class Circle : public Shape
{
public:
Circle(float r) { this->r = r; }
float GetArea() { return 3.14f * r * r; }
private:
float r;
};
int main()
{
Shape *a = new Circle(1.0f);
Shape *b = new Rectangle(1.0f);
cout << a->GetArea() << endl;
cout << b->GetArea() << endl;
}
An important thing to notice here is - you don't have to know the exact type of the class you're using, just the base type, and you will get the right result. This is very useful in more complex systems as well.
Have fun learning!
Have you ever added two integers with +, and then later added an integer to a floating-point number with +?
Have you ever logged x.toString() to help you debug something?
I think you probably already appreciate polymorphism, just without knowing the name.
In a strictly typed language, polymorphism is important in order to have a list/collection/array of objects of different types. This is because lists/arrays are themselves typed to contain only objects of the correct type.
Imagine for example we have the following:
// the following is pseudocode M'kay:
class apple;
class banana;
class kitchenKnife;
apple foo;
banana bar;
kitchenKnife bat;
apple *shoppingList = [foo, bar, bat]; // this is illegal because bar and bat is
// not of type apple.
To solve this:
class groceries;
class apple inherits groceries;
class banana inherits groceries;
class kitchenKnife inherits groceries;
apple foo;
banana bar;
kitchenKnife bat;
groceries *shoppingList = [foo, bar, bat]; // this is OK
Also it makes processing the list of items more straightforward. Say for example all groceries implements the method price(), processing this is easy:
int total = 0;
foreach (item in shoppingList) {
total += item.price();
}
These two features are the core of what polymorphism does.
Advantage of polymorphism is client code doesn't need to care about the actual implementation of a method.
Take look at the following example.
Here CarBuilder doesn't know anything about ProduceCar().Once it is given a list of cars (CarsToProduceList) it will produce all the necessary cars accordingly.
class CarBase
{
public virtual void ProduceCar()
{
Console.WriteLine("don't know how to produce");
}
}
class CarToyota : CarBase
{
public override void ProduceCar()
{
Console.WriteLine("Producing Toyota Car ");
}
}
class CarBmw : CarBase
{
public override void ProduceCar()
{
Console.WriteLine("Producing Bmw Car");
}
}
class CarUnknown : CarBase { }
class CarBuilder
{
public List<CarBase> CarsToProduceList { get; set; }
public void ProduceCars()
{
if (null != CarsToProduceList)
{
foreach (CarBase car in CarsToProduceList)
{
car.ProduceCar();// doesn't know how to produce
}
}
}
}
class Program
{
static void Main(string[] args)
{
CarBuilder carbuilder = new CarBuilder();
carbuilder.CarsToProduceList = new List<CarBase>() { new CarBmw(), new CarToyota(), new CarUnknown() };
carbuilder.ProduceCars();
}
}
Polymorphism is the foundation of Object Oriented Programming. It means that one object can be have as another project. So how does on object can become other, its possible through following
Inheritance
Overriding/Implementing parent Class behavior
Runtime Object binding
One of the main advantage of it is switch implementations. Lets say you are coding an application which needs to talk to a database. And you happen to define a class which does this database operation for you and its expected to do certain operations such as Add, Delete, Modify. You know that database can be implemented in many ways, it could be talking to file system or a RDBM server such as MySQL etc. So you as programmer, would define an interface that you could use, such as...
public interface DBOperation {
public void addEmployee(Employee newEmployee);
public void modifyEmployee(int id, Employee newInfo);
public void deleteEmployee(int id);
}
Now you may have multiple implementations, lets say we have one for RDBMS and other for direct file-system
public class DBOperation_RDBMS implements DBOperation
// implements DBOperation above stating that you intend to implement all
// methods in DBOperation
public void addEmployee(Employee newEmployee) {
// here I would get JDBC (Java's Interface to RDBMS) handle
// add an entry into database table.
}
public void modifyEmployee(int id, Employee newInfo) {
// here I use JDBC handle to modify employee, and id to index to employee
}
public void deleteEmployee(int id) {
// here I would use JDBC handle to delete an entry
}
}
Lets have File System database implementation
public class DBOperation_FileSystem implements DBOperation
public void addEmployee(Employee newEmployee) {
// here I would Create a file and add a Employee record in to it
}
public void modifyEmployee(int id, Employee newInfo) {
// here I would open file, search for record and change values
}
public void deleteEmployee(int id) {
// here I search entry by id, and delete the record
}
}
Lets see how main can switch between the two
public class Main {
public static void main(String[] args) throws Exception {
Employee emp = new Employee();
... set employee information
DBOperation dboper = null;
// declare your db operation object, not there is no instance
// associated with it
if(args[0].equals("use_rdbms")) {
dboper = new DBOperation_RDBMS();
// here conditionally, i.e when first argument to program is
// use_rdbms, we instantiate RDBM implementation and associate
// with variable dboper, which delcared as DBOperation.
// this is where runtime binding of polymorphism kicks in
// JVM is allowing this assignment because DBOperation_RDBMS
// has a "is a" relationship with DBOperation.
} else if(args[0].equals("use_fs")) {
dboper = new DBOperation_FileSystem();
// similarly here conditionally we assign a different instance.
} else {
throw new RuntimeException("Dont know which implemnation to use");
}
dboper.addEmployee(emp);
// now dboper is refering to one of the implementation
// based on the if conditions above
// by this point JVM knows dboper variable is associated with
// 'a' implemenation, and it will call appropriate method
}
}
You can use polymorphism concept in many places, one praticle example would be: lets you are writing image decorer, and you need to support the whole bunch of images such as jpg, tif, png etc. So your application will define an interface and work on it directly. And you would have some runtime binding of various implementations for each of jpg, tif, pgn etc.
One other important use is, if you are using java, most of the time you would work on List interface, so that you can use ArrayList today or some other interface as your application grows or its needs change.
Polymorphism allows you to write code that uses objects. You can then later create new classes that your existing code can use with no modification.
For example, suppose you have a function Lib2Groc(vehicle) that directs a vehicle from the library to the grocery store. It needs to tell vehicles to turn left, so it can call TurnLeft() on the vehicle object among other things. Then if someone later invents a new vehicle, like a hovercraft, it can be used by Lib2Groc with no modification.
I guess sometimes objects are dynamically called. You are not sure whether the object would be a triangle, square etc in a classic shape poly. example.
So, to leave all such things behind, we just call the function of derived class and assume the one of the dynamic class will be called.
You wouldn't care if its a sqaure, triangle or rectangle. You just care about the area. Hence the getArea method will be called depending upon the dynamic object passed.
One of the most significant benefit that you get from polymorphic operations is ability to expand.
You can use same operations and not changing existing interfaces and implementations only because you faced necessity for some new stuff.
All that we want from polymorphism - is simplify our design decision and make our design more extensible and elegant.
You should also draw attention to Open-Closed Principle (http://en.wikipedia.org/wiki/Open/closed_principle) and for SOLID (http://en.wikipedia.org/wiki/Solid_%28Object_Oriented_Design%29) that can help you to understand key OO principles.
P.S. I think you are talking about "Dynamic polymorphism" (http://en.wikipedia.org/wiki/Dynamic_polymorphism), because there are such thing like "Static polymorphism" (http://en.wikipedia.org/wiki/Template_metaprogramming#Static_polymorphism).
You don't need polymorphism.
Until you do.
Then its friggen awesome.
Simple answer that you'll deal with lots of times:
Somebody needs to go through a collection of stuff. Let's say they ask for a collection of type MySpecializedCollectionOfAwesome. But you've been dealing with your instances of Awesome as List. So, now, you're going to have to create an instance of MSCOA and fill it with every instance of Awesome you have in your List<T>. Big pain in the butt, right?
Well, if they asked for an IEnumerable<Awesome>, you could hand them one of MANY collections of Awesome. You could hand them an array (Awesome[]) or a List (List<Awesome>) or an observable collection of Awesome or ANYTHING ELSE you keep your Awesome in that implements IEnumerable<T>.
The power of polymorphism lets you be type safe, yet be flexible enough that you can use an instance many many different ways without creating tons of code that specifically handles this type or that type.
Tabbed Applications
A good application to me is generic buttons (for all tabs) within a tabbed-application - even the browser we are using it is implementing Polymorphism as it doesn't know the tab we are using at the compile-time (within the code in other words). Its always determined at the Run-time (right now! when we are using the browser.)