We had a scenario where we had to sort a object based on name and also the List Object inside that based on name. Please find the below Java objects.
Make class
class Make implements comparable<Make> {
String name;
List<Model> models;
....
getter..
setters..
#Override
public intcompareTo(object o) {
return name.compareTo(o.name);
}
}
Model Class
class Model implements comparable<Model> {
String name ;
....
getter..
setters..
#Override
public intcompareTo(object o) {
return name.compareTo(o.name);
}
}
Main Class
class main {
public static void main(String[] args) {
List<Make> make = new ArrayList<Make>();
Make make1 = new Make();
make1.addName("B");
Model model1 = new Model()
model1.setName ("B");
make1.addModel(model1);
Model model2 = new Model()
model2.setName ("A");
make1.addModel(model2);
make.add(make1);
// This will sort the make Object but not the model.
collections.sort(make);
}
}
We wanted to sort both Make and Model on Name.
How to sort both the make Models in the above scenario.?
Iterate through each Make object element and sort it's List field
for(Make makeElement : make)
{
Collections.sort(makeElement.models);
}
Personally I would go with #James solution.
but if you really really want to sort everything with one call (NOTE internally is many many calls :) )
change Make.intcompareTo(object 0) to :
public intcompareTo(object 0)
{
if(models!=null){
Collection.sort(models);
}
return name.compareTo(o.name);
}
Related
public class InventorySetDAO{
public LinkedList<CustomInventory> inventories = new LinkedList<>();
}
I am developing plugin that add/delete data in arraylist. and There's too much reference on the arrayList from other class.
Class InventoryItemModifier:
public class InventoryItemModifier {
InventorySetDAO inventorySetDAO;
public InventoryItemModifier(InventorySetDAO inventorySetDAO){
this.inventorySetDAO = inventorySetDAO;
}
public void addItem(ItemStack itemStack, ClickAction click, RequiredItems requiredItems) {
Bukkit.getPluginManager().callEvent(new ItemAddedEvent());
inventorySetDAO.getLastInventory().addItem(itemStack, click, requiredItems);
}
public void removeItem(ItemStack itemStack){
Bukkit.getPluginManager().callEvent(new ItemRemovedEvent());
inventorySetDAO.getLastInventory().removeItem(itemStack);
}
}
Class InventoryPlayerAccessor:
public class InventoryPlayerAccessor {
InventorySetDAO inventorySetDAO;
public boolean openPage(Player player) {
if (!inventories.isEmpty()) {
inventories.get(0).openInventory(player);
return true;
}
return false;
}
public boolean openPage(Player player, int index) {
if (!inventories.isEmpty()) {
if (index >= 0 && index < inventories.size()) {
inventories.get(index).openInventory(player);
return true;
}
}
return false;
}
}
I think there is risk of manipualte arrayList unproperly, so I think arrayList must be in a class and provide methods(add/insert/remove...) but if then there are too much responsibilities in that class.
I tried to seperate them into multiple classes, but it doesn't seem to solve this problem. is there a way to reduce reliance on arrayList, or efficient way to encapsulate arrayList?
To reduce each classes reliance on the underlying ArrayList (or just List), you could think about using the composite pattern instead of the DAO pattern. This would hide all/most of the logic to the InventorySet class.
class InventorySet {
private final List<CustomInventory> inventories = new ArrayList<>();
public void addItem() { }
public void removeItem() { }
}
Then, you can just keep your InventoryPlayerAccessor (maybe rename) but compose it of a InventorySet for easy access.
class InventorySetView {
void open();
}
As you can see from the image below I want to select something from my table ( which changes whenever I press a button from the vertical box to the left i.e "Overview", "Orders" ... ) and delete the record from an array ( i.e. where the content comes from ).
The method I approached bellow works but it is not elegant since I have to create at most 8 if statements for each button id. Is there any way to delete the content dynamically. Is there any way for the JVM to figure out which record belongs to which array list?
TableController
#FXML
private TableView<Object> defaultTableView;
public void delete(){
if( MockServer.getServer().currentButton.equals("btnIngredients"))
MockServer.getServer().removeIngredient(defaultTableView.getSelectionModel().getSelectedItem());
else if ( MockServer.------.equals("btnOrders"))
MockServer.getServer().removeOrder(defaultTableView.getSelectionModel().getSelectedItem());
}
Controller
#FXML
private TableController tableController;
#FXML
public void deleteRecord(ActionEvent event){
tableController.delete();
}
MockServer
public class MockServer implements ServerInterface {
public Restaurant restaurant;
public ArrayList<Dish> dishes = new ArrayList<Dish>();
public ArrayList<Drone> drones = new ArrayList<Drone>();
public ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>();
public ArrayList<Order> orders = new ArrayList<Order>();
public ArrayList<Staff> staff = new ArrayList<Staff>();
public MockServer(){}
public ArrayList<Ingredient> getIngredients() { return this.ingredients; }
public ArrayList<Order> getOrders() { return this.orders; }
public ArrayList<Staff> getStaff() { return this.staff; }
....
static public ServerInterface getServer(){
return server;
}
#Override
public void removeIngredient(Ingredient ingredient) {
int index = this.ingredients.indexOf(ingredient);
this.ingredients.remove(index);
this.notifyUpdate();
}
}
This pseudocode will need refactoring since I don't have all the code that you are using but I wish that you will get the general idea
Ok I believe that in the button click code you have to tell your mock server which list is currently used try adding this to the mock server
List currentList = null;
public void setCurrentList(String listName) { // you can use integer but the best is to use enum type setCurrentList(enum) this way you will get tapeSafety
switch(listName){
case "ingredients" : currentList = ingredients ; break;
//other cases
default : throw new Exception(" list not referred error with key value"+listName);
}
}
public void delete(Object o){
int index = this.currentList.indexOf(o);
this.currentList.remove(index);
}
now you can update you controller delete as bellow
public void delete(){
MockServer.getServer().delete(defaultTableView.getSelectionModel().getSelectedItem());
}
Why this should work?
you have to know that there is a good practice that says code to an interface, not an implementation
As you know List in java is an interface so when I assigned the ingredients object this interface will reference the same ArrayList as the object and it will take all it behaviours (how to search for an ingredient object etc...) this way when we will use the currentList on runtime after a button click we are sure that the currentList will be the same as the clicked list and pointing to the same list in the memory
Wish this simple and really resume explanation could help you
I am creating a dump Java app for student information system for learning and implementing OOPS Concepts like inheritance, abstraction, polymorphism and encapsulation.
What I am doing is, I have created Faculty Class, Student Class and a College Class. Now i want to add new faculty in College. So my approach is to create a method in College class i.e. addFaculty(Faculty f) and fireFaculty(Faculty f), now i want to add Faculties in College class.
Whats the best way to do it? How do i store list of Faculty Object in College Object. Because i can add more than one faculty and more than one student in college.
Whats the best approach to solve this problem in OOPS?
Here is College.java code which i have implemented, it works fine but is this the best way i can solve it?
public class College
{
String name;
String location;
String courses[];
HashMap<String,Faculty> faculties;
int noOfFaculties = 0;
int noOfStudents = 0;
public College(String name,String location,String courses[])
{
this.name = name;
this.location = location;
this.courses = courses;
faculties = new HashMap<>();
}
public void addFaculty(Faculty faculty)
{
faculties.put(faculty.getName(),faculty);
}
public void printFaculties()
{
Set<String> set = faculties.keySet();
if(set.size()>0)
{
for(String s:set)
{
System.out.println(faculties.get(s).getName());
}
}
else
{
System.out.println("No Faculties Currently Working");
}
}
public void fireFaculty(Faculty faculty)
{
faculties.remove(faculty.getName());
}
public String getName()
{
return name;
}
public String getLocation()
{
return location;
}
public String[] getCourses()
{
return courses;
}
}
If you cannot have duplicates use HashSet<Faculty> if you dont mind use a List<Faculty>.
Example:
class College {
private List<Faculty> listFactories = new ArrayList<>(); // dupes allowed
private Set<Faculty> setFactories = new HashSet<>(); // no dupes allowed
}
Check collections API.
There's a ton of ways you can do it. Probably the easiest way to handle storing a collection of objects is by using one of the Collections provided by Java. For beginners, probably the easiest one to understand is an ArrayList, which is basically an array that grows in size dynamically depending on the amount of objects in the collection.
So, as an axample, your code might be something like this:
public class College
{
private ArrayList<Faculty> faculty;
public College()
{
faculty = new ArrayList<Faculty>();
}
public void addFaculty(Faculty f)
{
faculty.add(f);
}
public void fireFaculty(Faculty f)
{
faculty.remove(f);
}
}
imho It depends what kind of services College college offers. If I were coding, I would start with:-
List<Faculy> faculties = new ArrayList<>();
....
public void addFaculty(Faculty f) {
faculties.add(f);
}
//... etc
And change to an altearnative later if needed.
I have an object, Supply, that can either be an ElecSupply or GasSupply (see related question).
Regardless of which subclass is being edited, they all have a list of BillingPeriods.
I now need to instantiate N number of BillingPeriodEditors based on the contents of that list, and am pretty baffled as to how I should do it.
I am using GWTP. Here is the code of the SupplyEditor I have just got working:
public class SupplyEditor extends Composite implements ValueAwareEditor<Supply>
{
private static SupplyEditorUiBinder uiBinder = GWT.create(SupplyEditorUiBinder.class);
interface SupplyEditorUiBinder extends UiBinder<Widget, SupplyEditor>
{
}
#Ignore
final ElecSupplyEditor elecSupplyEditor = new ElecSupplyEditor();
#Path("")
final AbstractSubTypeEditor<Supply, ElecSupply, ElecSupplyEditor> elecSupplyEditorWrapper = new AbstractSubTypeEditor<Supply, ElecSupply, ElecSupplyEditor>(
elecSupplyEditor)
{
#Override
public void setValue(final Supply value)
{
setValue(value, value instanceof ElecSupply);
if(!(value instanceof ElecSupply))
{
showGasFields();
}
else
{
showElecFields();
}
}
};
#Ignore
final GasSupplyEditor gasSupplyEditor = new GasSupplyEditor();
#Path("")
final AbstractSubTypeEditor<Supply, GasSupply, GasSupplyEditor> gasSupplyEditorWrapper = new AbstractSubTypeEditor<Supply, GasSupply, GasSupplyEditor>(
gasSupplyEditor)
{
#Override
public void setValue(final Supply value)
{
setValue(value, value instanceof GasSupply);
if(!(value instanceof GasSupply))
{
showElecFields();
}
else
{
showGasFields();
}
}
};
#UiField
Panel elecPanel, gasPanel, unitSection;
public SupplyEditor()
{
initWidget(uiBinder.createAndBindUi(this));
gasPanel.add(gasSupplyEditor);
elecPanel.add(elecSupplyEditor);
}
// functions to show and hide depending on which type...
#Override
public void setValue(Supply value)
{
if(value instanceof ElecSupply)
{
showElecFields();
}
else if(value instanceof GasSupply)
{
showGasFields();
}
else
{
showNeither();
}
}
}
Now, as the list of BillingPeriods is a part of any Supply, I presume the logic for this should be in the SupplyEditor.
I got some really good help on the thread How to access PresenterWidget fields when added dynamically, but that was before I had implemented the Editor Framework at all, so I think the logic is in the wrong places.
Any help greatly appreciated. I can post more code (Presenter and View) but I didn't want to make it too hard to read and all they do is get the Supply from the datastore and call edit() on the View.
I have had a look at some examples of ListEditor but I don't really get it!
You need a ListEditor
It depends of how you want to present them in your actual view, but the same idea apply:
public class BillingPeriodListEditor implements isEditor<ListEditor<BillingPeriod,BillingPeriodEditor>>, HasRequestContext{
private class BillingPeriodEditorSource extends EditorSource<BillingPeriodEditor>{
#Override
public EmailsItemEditor create(final int index) {
// called each time u add or retrive new object on the list
// of the #ManyToOne or #ManyToMany
}
#Override
public void dispose(EmailsItemEditor subEditor) {
// called each time you remove the object from the list
}
#Override
public void setIndex(EmailsItemEditor editor, int index) {
// i would suggest track the index of the subeditor.
}
}
private ListEditor<BillingPeriod, BillingPeriodEditor> listEditor = ListEditor.of(new BillingPeriodEditorSource ());
// on add new one ...
// apply or request factory
// you must implement the HasRequestContext to
// call the create.(Proxy.class)
public void createNewBillingPeriod(){
// create a new one then add to the list
listEditor.getList().add(...)
}
}
public class BillingPeriodEditor implements Editor<BillingPeriod>{
// edit you BillingPeriod object
}
Then in you actual editor edit as is in the path Example getBillingPeriods();
BillingPeriodListEditor billingPeriods = new BillingPeriodListEditor ();
// latter on the clickhandler
billingPeriods.createNewBillingPeriod()
You are done now.
I have a object graph which goes like this:
root
: childs (array)
: childs (array)
I am building a JSON response out of this so I need to loop through each collection creating code like this:
// code for root
// loop through direct root childs
for (Child child : childs) {
// Loop through the childs of the object in current context.
for (AnotherChild anotherChild : moreChilds) {
}
}
How do you avoid such code? It will be an arrow in the end. I could have created own methods for each level of for loop, but is that a good approach? Are there other approaches which is better?
If we are talking about this specific problem (building a JSON response) you use some kind of serializer like jackson or write a custom one. There is a relevant question on this topic https://stackoverflow.com/questions/338586/a-better-java-json-library
On the other hand for some other uses you can use a more functional approach like Guava or Lambdaj.
But when it comes done to big O complexity these are not much of a help there, so you may wanna try different approach if possible then.
That's a recursive structure, then you should use recursion to handle nesting. A depth first visit should do.
edit to interface JSON you would really follow the advice by #Mite Mitreski, for a recursive visit pseudocode sample:
void visit(Child tree) {
json_write_class(tree);
for (Attribute a : tree.attributes) {
json_write_attr(a);
if (tree.children != null) {
json_push_indent();
for (Child child : tree.children) {
visit(child);
}
json_pop_indent();
}
}
If you need more control, you could write kind of 'semantic actions' on nodes of that tree to establish the attributes, and implement the visitor pattern to output the data (more verbose than the first alternative).
Frequently helps to use the analogy of grammars and syntax trees, these are the most obvious sample we (as programmers) are used to.
I think you have a nasty design issue there, as the class that is doing all those loops knows a hell lot of the other classes (and thus breaking the Law of Demeter).
An approach I try to use (that I've learn from some very experienced developers) is to wrap collections (or arrays) in their own classes; and then create methods that iterate over the array/collection performing one operation. In this case, it could be calling another method in another class that wraps a collection.
In this way, each class has very little knowledge of what the other classes do (or the internals of the child objects).
Edit
Here's an example. Imagine that you have an account in a website similar to amazon. In that account, you have associated a few credit cards.
So, instead of having
class Account {
List<CreditCard> creditCards;
public CreditCard getPrimaryCard() {
//complex code to find the primary credit card
}
//lots of other code related to the account and credit cards
}
you can do
class Account {
CreditCards creditCards;
public CreditCard getPrimaryCard() {
creditCards.getPrimaryCard()
}
//lots of other code related to the account
}
class CreditCards {
List<CreditCard> creditCards;
public CreditCard getPrimaryCard() {
//complex code to find the primary credit card
}
public void addCard(CreditCard creditCard) {
//complex logic to validate that the card is not duplicated.
}
//lots of other code related to credit cards
}
In this way, Account doesn't need to know about how the creditCards are stored in memory (should it be a list? or a set? or get it from a remote webservice?)
Please bear in mind that this is a trivial example.
You could provide interface which all interested class should implement. That interface should provide method to converting a current object to JSON. See example:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class JsonProgram {
public static void main(String[] args) {
Root root = new Root(Arrays.asList(new Child(Arrays.asList(
new AnotherChild(1), new AnotherChild(2)))));
System.out.println(root.toJSON());
}
}
interface JsonState {
String toJSON();
}
class Root implements JsonState {
private List<Child> childs = new ArrayList<Child>();
public Root(List<Child> childs) {
this.childs = childs;
}
#Override
public String toJSON() {
StringBuilder builder = new StringBuilder();
builder.append("{").append("\"childs\"").append(":[");
int index = 0;
for (Child child : childs) {
builder.append(child.toJSON());
if (index < childs.size() - 1) {
builder.append(",");
}
index++;
}
builder.append("]\"}");
return builder.toString();
}
}
class Child implements JsonState {
private List<AnotherChild> anotherChilds = new ArrayList<AnotherChild>();
public Child(List<AnotherChild> anotherChilds) {
this.anotherChilds = anotherChilds;
}
#Override
public String toJSON() {
StringBuilder builder = new StringBuilder();
builder.append("{").append("\"anotherChilds\"").append(":[");
int index = 0;
for (AnotherChild child : anotherChilds) {
builder.append(child.toJSON());
if (index < anotherChilds.size() - 1) {
builder.append(",");
}
index++;
}
builder.append("]}");
return builder.toString();
}
}
class AnotherChild implements JsonState {
private int value;
public AnotherChild(int value) {
this.value = value;
}
#Override
public String toJSON() {
StringBuilder builder = new StringBuilder();
builder.append("{").append("\"value\"").append(":\"").append(value)
.append("\"}");
return builder.toString();
}
}
Output:
{
"childs":[
{
"anotherChilds":[
{
"value":"1"
},
{
"value":"2"
}
]
}
]
}
But it is not a good solution. Instead of implementing Your own solution You should use some library which can do it for You. I recommend to You google-gson. For me is the best.
EDIT - GSON EXAMPLE
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonProgram {
public static void main(String[] args) {
Root root = new Root(Arrays.asList(new Child(Arrays.asList(
new AnotherChild(1), new AnotherChild(2)))));
Gson gson = new GsonBuilder().serializeNulls().create();
System.out.println(gson.toJson(root));
}
}
class Root {
private List<Child> childs = new ArrayList<Child>();
public Root(List<Child> childs) {
this.childs = childs;
}
#Override
public String toString() {
return Arrays.toString(childs.toArray());
}
}
class Child {
private List<AnotherChild> anotherChilds = new ArrayList<AnotherChild>();
public Child(List<AnotherChild> anotherChilds) {
this.anotherChilds = anotherChilds;
}
#Override
public String toString() {
return Arrays.toString(anotherChilds.toArray());
}
}
class AnotherChild {
private int value;
public AnotherChild(int value) {
this.value = value;
}
#Override
public String toString() {
return Integer.toString(value);
}
}
Above example create same output. For me this is a more elegant solution.