Vector<Customer> C++, List<Customer> & Vector<Customer> Java - java

I learned this piece of code in University, while learning C++.. and I later used the same thing in C#... but now I want to use it in Java... I have looked all over Internet for similar thing, but i dun even no how to phrase it so i get the correct results.
So umm please let me know how to do this is in JAVA and also let me know what is this way called??? I know What it does.. but i have no idea how it does it.. so mind explaining it as well...
C++ is the same thing as below except one DIFFERENCE look Below
C# if (Customers[i].delExecute(delIn) == true)
C++ if (Customers[i]->delExecute(delIn) == true)
Java ?? if (????????????????????????????????)
So here I go ill try my best to explain.
C#
Class called Customer with custId etc etc
List<Customer> Customers = new List<Customers>
public void delCust(int delIn)
{
for (int i = 0; i < Customers.Count(); i++)
{
if (Customers[i].delExecute(delIn) == true)
{
Customers.Remove(Customers[i]);
break;
}
}
}
bool delExecute(int delInput) {
if (custId == delInput) {
return true;
}
return false;
}
OK right so the above code works
now I want the same thing with JAVA... anyone got any ideas how?

if (Customers.get(i).delExecute(delIn))
BTW, there is no need to say == true explicitly

In Java, Vector is an out-dated class which you should probably avoid using. Instead, you should use an ArrayList. Either way, though, both are Lists, and thus implement get for random-access.
You can implement what you're attempting as follows...
if (customers.get(i).delExecute(delIn))
Note that == true is redundant, as it is effectively an identity (true == true is true, false == true is false). You should also avoid capitalized field names in Java.
Now, there is also a preferred way to do what you are attempting using an Iterator.
private List<Customer> customers = new ArrayList<Customers>();
public void delCust(int delIn) {
final Iterator<Customer> cursor = customers.iterator();
while (cursor.hasNext()) {
if (cursor.next().delExecute(delIn)) {
cursor.remove();
break;
}
}
}
... coupled with:
boolean delExecute(int delInput) {
return custId == delInput;
}

Related

Convert nested loops into a Stream

I want to replace nested for loops in the following code with streams:
private boolean check(St st) {
List<Co> prereqs = getCoPrereqs();
for (Co prereq : prereqs) {
List<En> stEns = st.getEns();
boolean flag = false;
for (En en : stEns) {
if (en.getCo().equals(prereq) && en.getGr() != null) {
if (en.hasPassedCo()) {
flag = true;
}
}
if (!flag)
return false;
}
}
return true;
}
The two loops and the variable flag is causing confusion. I am not sure if this can be converted to streams totally.
I have simplified your code somewhat by doing the following:
removing the boolean flag. It isn't necessary.
get the List<En> just one time outside of the Prereq loop. You can reiterate the original as often as necessary.
The major difference is to check for a false return from en.hasPassedCo() and return false immediately. Once the iterations are complete, then return true.
private boolean check(St st) {
List<Co> prereqs = getCoPrereqs();
List<En> stEns = st.getEns();
for (Co prereq : prereqs) {
for (En en : stEns) {
if (en.getCo().equals(prereq) && en.getGr() != null) {
if (!en.hasPassedCo()) {
return false;
}
}
}
}
return true;
}
I'm not certain that streams would improve this (at least not knowing more about the relationships of the fields to each other). Also, it doesn't make sense how Co relates to en.getCo. Seems to me that something like prereqs.contains(en.getCo()) would be more appropriate.
Probably, you can use nested streams with allMatch.
I'm saying "probably" because I can't be sure that the code you've proved does what expected, types name are not self-explanatory at all (names in the code matter a lot) and you have not accompanied the code with any explanations.
If I understood your code correctly, you need to validate every Co object returned by getCoPrereqs() and that entails checking each Co object against En object from a List<En> which should be extracted from the method parameter.
That's how it might look like:
private boolean check(St st){
return getCoPrereqs().stream()
.allMatch((Co prereq) -> st.getEns().stream()
.allMatch((En en) -> en.getCo().equals(prereq)
&& en.getGr() != null
&& en.hasPassedCo()
));
}
For readability reasons (to make it more easier to compare stream with loops), I've used explicitly typed lambda expressions (the common practice is to omit types for brevity and let the type inference do the job).

Refactoring approach to clean up many if elses with the help of java lambdas

Currently I am cleaning up hard to maintain and test if else clutter which is based on conditions which have to be checked in isolations:
What is the basic semantic of the conditions?
Big Entity Objects have to be checked based on two entity keys namely Trans and Right for state change as in the example Below:
if (oldTrans.getfOrder().equals(newTrans.getfOrder()) {
compound.setIsStateChanged(true);
return;
}
if (oldRight.getfRight().equals(newRight.getfRight()) {
compound.setIsStateChanged(true);
}
Currently the if else are all cluttered up at one place:
if (oldTrans.getfOrder().equals(newTrans.getfOrder()) {
compound.setIsStateChanged(true);
LOGGER.info("major change detected");
return compound;
} if (oldTrans.getgOrder().equals(newTrans.getgOrder()) {
compound.setIsStateChanged(true);
LOGGER.info("major change detected");
return compound;
}
I see 2 main issues here
Every if has a return statement and with so many ifs it hard to know when and a what point method exits.
To many if branchings are error prone and The number of conditions is likely to go up.
To avoid so many ifs that are basically based on the same semantic underneath from clean code perspective I tried to solve it the polymorphic way
Extracting the Conditions in Enums as Constants and impleneting a checker Interface that takes new and old objects as params
public interface ICheckStateChange<T>(T old, T new) {
boolean check(T old, T new);
}
//implementations
public TransChecker implements ICheckStateChange<Trans> {
List<BiPredicate<Trans, Trans>> allTransConditions = transConditions.getValues();
public boolean check(Trans oldTrans, Trans newTrans) {
//all conditions null check here
//loop through conditions
for (BiPredicate<Trans, Trans> transCondition: allTransConditions) {
if (transCondition).test()) {
return true;
LOGGER.info("major state change detected, taking apt action")
}
}
public RightChecker implements ICheckStateChange<Right> {
List<BiPredicate<Right, Right>> allTransConditions = RightConditions.getValues();
public boolean check(Right oldRight, Right newRIght) {
//all conditions null check here
//loop through conditions
for (BiPredicate<Right, Right> rightCondition: allRightConditions) {
if (rightCondition).test()) {
return true;
LOGGER.info("major state change detected, taking apt action")
}
}
The Conditons are now centrally located as BiPredicate constants using lambdas
public enum rightConditions {
FORDER_CHANGE_NULL_TO_NOT_NULL((Order old, Order new)
-> old == null && new != null),
//to be replaced by the right condition
GORDER_CHANGE_FROM_OPEN_TO_DONE((Order old, Order new)
-> old == null && new != null)
//to be replaced by the right condition
LORDER_CHANGE_FROM_OPEN_TO_REVERTED((Order old, Order new)
-> old == null && new != null)
........
}
My question here is about the approach of refactoring the If elses with the help of lambda BiPredicates in hinddight of clean code? Readability, extensibility and maintainability ;)

Java Collections.Sort Comparison method violates its general contract

I'm getting an error in my code since yesterday and I'm not sure why!
I googled a lot and found this Stack-Post.
I use this funtion to sort users by name and create date.
This function has worked since 2 years and now I'm getting an error for one user and I don't know what has changed.
I tried to check my data if there is anything corrupt but couldn't find anything wrong.
After reading zhe Stack-Post I still didn't understand fully what's the problem or what has changed in my project.
public void sortUsers(List<Users> sortList) {
Collections.sort(sortList, new Comparator<Users>() {
public int compare(Users user1, Users user2) {
Integer comp = 0;
comp = user1.getUsername().compareTo(user2.getUsername());
if (comp == 0) {
comp = user1.getCreateDate().before(user2.getCreateDate()) ? -1 : 1;
}
return comp;
}
});
}
comp = user1.getCreateDate().before(user2.getCreateDate()) ? -1 : 1;
This line can never return zero, in the case that the dates are equal. This means that it's not anti-symmetric (i.e. sgn(a.compareTo(b)) = -sgn(b.compareTo(a))).
The exact fix depends on what class getCreateDate() returns, but it could be something like:
comp = user1.getCreateDate().compareTo(user2.getCreateDate());
However, an easier way to do construct a compliant comparator would be:
Comparator.comparing(Users::getUsername).thenComparing(Users::getCreateDate)
or similar.

Why does the equals() implementation generated by Eclipse check for null before type checking (instanceof)?

I regularly used Eclipse's code generation tools (Source / Generate hashCode() and equals()...) to create the equals() implementation for simple POJO classes. If I choose to "Use instanceof to compare types" this produces an equals() implementation similar to this:
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MyClass)) {
return false;
}
MyClass other = (MyClass) obj;
// check the relevant fields for equality
}
Today a colleague pointed out, that the second if statement is not necessary at all, since the instanceof type check will return false whenever obj is null. (See question 3328138.)
Now, I guess that the folks writing the code templates for Eclipse JDT are worth their salt, too. So I figure there must be some reason for that null check, but I'm not really sure what it is?
(Also question 7570764 might give a hint: if we use getClass() comparison for type checking instead instanceof, obj.getClass() is not null safe. Maybe the code template is just not clever enough to omit the null check if we use instanceof.)
EDIT: Dragan noticed in his answer, that the instanceof type check is not the default setting in Eclipse, so I edited that out of the question. But that does not change anything.
Also please do not suggest that I should use getClass() or (even better!) a different IDE. That's not the point, that does not answer the question. I didn't ask for advice on how to write an equals() implementation, whether to use instanceof or getClass(), etc.
The question roughly is: is this a minor bug in Eclipse? And if it's not, then why does it qualify as a feature?
It is unnecessary because instanceof has a built in null check.
But instanceof is a lot more than a simple foo == null. It is a full instruction preparing a class check doing unnecessary work before the null check is done. (see for more details http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.instanceof)
So a separate null check could be a performance improvement.
Did a quick measurement and no surprise foo==null is faster than a nullcheck with instanceof.
But usually you do not have a ton of nulls in an equals() leaving you with a duplicate unnecessary nullcheck most of the times... which will likely eat up any improvement made during null comparisons.
My conclusion: It is unnecessary.
Code used for testing for completeness (remember to use -Djava.compiler=NONE else you will only measure the power of java):
public class InstanceOfTest {
public static void main(String[] args) {
Object nullObject = null;
long start = System.nanoTime();
for(int i = Integer.MAX_VALUE; i > 0; i--) {
if (nullObject instanceof InstanceOfTest) {}
}
long timeused = System.nanoTime() - start;
long start2 = System.nanoTime();
for(int i = Integer.MAX_VALUE; i > 0; i--) {
if (nullObject == null) {}
}
long timeused2 = System.nanoTime() - start2;
System.out.println("instanceof");
System.out.println(timeused);
System.out.println("nullcheck");
System.out.println(timeused2);
}
}
Indeed, it is unnecessary and it is the mistake of the authors of the Eclipse template. And it is not the first one; I found more of smaller errors there. For example, the generation of the toString() method when I want to omit null values:
public class A {
private Integer a;
private Integer b;
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("A [");
if (a != null)
builder.append("a=").append(a).append(", ");
if (b != null)
builder.append("b=").append(b);
builder.append("]");
return builder.toString();
}
}
If a is not null and b is, there will be an extra comma before the closing ].
So, regarding your statement: "Now, I guess that the folks writing the code templates for Eclipse JDT are worth their salt, too.", I assume they are, but it would not hurt them to pay more attention to these tiny inconsistencies. :)

A cleaner if statement with multiple comparisons [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
The following statement just looks very messy when you have a lot of terms:
if(a.equals("x") || a.equals("y") || a.equals("z") || Any number of terms...... )
//Do something
Is there a cleaner way of performing the same action, I would like my code to be as readable as possible.
NOTE: x, y and z are just placeholders for any string of any length. There could be 20 string terms here of variable length in if condition each being OR'd together
What do you think looks "unclean" about it?
If you have a bunch of complicated boolean logic, you might separate the different parts of it into individual boolean variables and refer to them in the if statement.
Or you could create a function that takes your 'a' variable and returns a boolean. You'd just be hiding your logic in the method, but it would clean up your if statement.
Set<String> stuff = new HashSet<String>();
stuff.add("x");
stuff.add("y");
stuff.add("z");
if(stuff.contains(a)) {
//stuff
}
If this is a tight loop you can use a static Set.
static Set<String> stuff;
static {
stuff = new HashSet<String>();
stuff.add("x");
stuff.add("y");
stuff.add("z");
}
//Somewhere else in the cosmos
if(stuff.contains(a)) {
//stuff
}
And if you want to be extra sure nothing is getting modified while you're not looking.
Set<String> test = Collections.unmodifiableSet(new HashSet<String>() {
{
add("x");
add("y");
add("z");
}
});
If you just want to get some logic in there for a handful of hard coded conditions then one of the switch or if statement with newlines solutions might be better. But if you have a lot of conditions then it might be good to separate your configuration from logic.
Alternatively, if you are using Java 7+ you can use strings in switch/case. For example (I extracted this from an Oracle doc and modified)
switch (str) {
case "x":
case "y":
case "z":
//do action
break;
default:
throw new IllegalArgumentException("argument not matched "+str);
}
Here is the link
Use a regular expression
If (a.matches("[xyz]")){
// matches either "x", "y", or "z"
or, for longer strings,
If (a.matches("one|two|three")){
// matches either "one", "two" or "three"
But this is computationally expensive, but probably not much worse than instantiating a set etc. But it's the clearest way I can think of.
But in the end, the nicest way is probably to leave things as they are, with an adjustment to the formatting:
if (a.equals("x") ||
a.equals("y") ||
a.equals("z")
){
There is then absolutely no ambiguity in what the code is doing and so your code will be easier to maintain. If performance matters, you can even put the most likely occurrences towards the top of the list.
Reaching for semantics
On a semantic level, what you are checking for is set membership. However, you implement it on a very low level, basically inlining all the code needed to achieve the check. Apart from forcing the reader to infer the intent behind that massive condition, a prominent issue with such an approach is the large number of degrees of freedom in a general Boolean expression: to be sure the whole thing amounts to just checking set membership, one must carefully inspect each clause, minding any parentheses, misspellings of the repeated variable name, and more.
Each loose degree of freedom means exposure to not just one more bug, but to one more class of bugs.
An approach which uses an explicit set would have these advantages:
clear and explicit semantics;
tight constraint on the degrees of freedom to look after;
O(1) time complexity vs. O(n) complexity of your code.
This is the code needed to implement a set-based idiom:
static final Set<String> matches =
unmodifiableSet(new HashSet<>(asList("a","b","c")));
...
if (matches.contains(a)) // do something;
*I'm implying import static java.util.Arrays.asList and import static java.util.Collections.unmodifiableSet
Readability Is Mostly Formatting
Not readable...
if(a.equals("x") || a.equals("y") || a.equals("z") || Any number of terms...... )
//Do something
Now easy to real...
if(a.equals("x") ||
a.equals("y") ||
a.equals("z") ||
Any number of terms...... )
//Do something
Readability is very subjective to the person reading the source code.
If I came across code that implements collections, loops or one of the many other complicated answers here. I'd shake my head in disbelieve.
Separate The Logic From The Problem
You are mixing two different things. There is the problem of making the business logic easy to read, and the problem of implementing the business logic.
if(validState(a))
// Do something
How you implement validState doesn't matter. What's important is that code with the if statement is readable as business logic. It should not be a long chain of Boolean operations that hide the intent of what is happening.
Here is an example of readable business logic.
if(!isCreditCard(a)) {
return false;
}
if(isExpired(a)) {
return false;
}
return paymentAuthorized(a);
At some level there has to be code that processes basic logic, strings, arrays, etc.. etc.. but it shouldn't be at this level.
If you find you often have to check if a string is equal to a bunch of other strings. Put that code into a string utility class. Separate it from your work and keep your code readable. By ensuring it shows what you're really trying to do.
You can use Arrays.asList().This is the simplest approach and less verbosity.
Arrays.asList("x","y","z"...).contains(a)
For performance reason if your collection is too big you could put data in a HashSet cause searching there is in constant time.
Example make your own util method
public final class Utils{
private Utils(){}//don't let instantiate
public static <T> boolean contains(T a,T ... x){
return new HashSet<>(Arrays.asList(x)).contains(a);
}
}
Then in your client code:
if(Utils.contains(a,"x","y","z","n")){
//execute some code
}
With a little bit of help, you can get the syntactic sugar of a nicer if-statement with just a tiny bit of overhead. To elaborate on Tim's recommendation and Jesko's recommendation a tad further...
public abstract class Criteria {
public boolean matchesAny( Object... objects ) {
for( int i = 0, count = objects.length; i < count; i++ ) {
Object object = objects[i];
if( matches( object ) ) {
return true;
}
}
return false;
}
public boolean matchesAll( Object... objects ) {
for( int i = 0, count = objects.length; i < count; i++ ) {
Object object = objects[i];
if( !matches( object ) ) {
return false;
}
}
return true;
}
public abstract boolean matches( Object object );
}
public class Identity extends Criteria {
public static Identity of( Object self ) {
return new Identity( self );
}
private final Object self;
public Identity( Object self ) {
this.self = self;
}
#Override
public boolean matches( Object object ) {
return self != null ? self.equals( object ) : object == null;
}
}
Your if-statement would then look like this:
if( Identity.of( a ).matchesAny( "x", "y", "z" ) ) {
...
}
This is sort of a middle ground between having a generic syntax for this sort of conditional matching and having the expression describe a specific intent. Following this pattern also lets you perform the same sort of matching using criteria other than equality, much like how Comparators are designed.
Even with the improved syntax, this conditional expression is still just a little bit too complex. Further refactoring might lead to externalizing the terms "x", "y", "z" and moving the expression into a method whose name clearly defines its intent:
private static final String [] IMPORTANT_TERMS = {
"x",
"y",
"z"
};
public boolean isImportant( String term ) {
return Identity.of( term ).matchesAny( IMPORTANT_TERMS );
}
...and your original if-statement would finally be reduced to...
if( isImportant( a ) ) {
...
}
That's much better, and now the method containing your conditional expression can more readily focus on Doing One Thing.
Independent of what you are trying to achieve, this
if(a.equals("x") || a.equals("y") || a.equals("z") || Any number of terms...... )
//Do something
is always messy and unclean. In the first place it is just too long to make sense of it quickly.
The simplest solution for me would be to express your intend instead of being explicit.
Try to do this instead:
public class SomeClass{
public void SomeMethod(){
if ( matchesSignificantChar(a) ){
//doSomething
}
}
private bool matchesSignificantChar(String s){
return (s.equals("x") || s.equals("y") || s.equals("z") || Any number of terms...... )
}
}
This simplifies the scope of your conditional statement and makes it easier to understand while moving the complexity to a much smaller and named scope, that is headed by your intend.
However, this is still not very extensible. If you try to make it cleaner, you can extract the boolean method into another class and pass it as a delegate to SomeClass'es Constructor or even to SomeMethod. Also you can look into the Strategy Pattern for even more exensiblity.
Keep in mind that as a programmer you will spend much more time reading code (not only yours) than writing it, so creating better understandable code will pay off in the long run.
I use following pattern
boolean cond = false; // Name this variable reasonably
cond = cond || a.equals("x");
cond = cond || a.equals("y");
cond = cond || a.equals("z");
// Any number of terms......
if (cond) {
// ...
}
Note: no objects created on the heap. Also you can use any conditions, not only "equals".
In ruby you can use operator ||= for this purpose like cond ||= a.equals("x").
The Set answer is good. When not comparing for membership of a collection you can also separate out some or all of the conditional statement into methods. For example
if (inBounds(x) && shouldProcess(x) ) {
}
If a is guaranteed to be of length 1, you could do:
if ("xyz".indexOf(a) != -1)
One really nice way to do something like this is to use ASCII values, assuming your actual case here is where a is a char or a single character string. Convert a to its ASCII integer equivalent, then use something like this:
If you want to check that a is either "t", "u", "v", ... , "z", then do.....
If (val >= 116 && val <= 122) {//code here}
I prefer to use regexp like few guys wrote upper.
But also you can use next code
private boolean isOneMoreEquals(Object arg, Object... conditions) {
if (conditions == null || arg == null) {
return false;
}
for (int i = 0, d = conditions.length; i < d; i++) {
if (arg.equals(conditions[i])) {
return true;
}
}
return false;
}
so your code will be next:
if (isOneMoreEquals(a, "x", "y", "z") {
//do something
}
Assuming that your "x", "y", and "z" can be of arbitrary length, you can use
if (0 <= java.util.Arrays.binarySearch(new String[] { "x", "y", "z" }, a)) {
// Do something
}
Just make sure that you list your items in lexicographic order, as required by binarySearch(). That should be compatible all the way back to Java 1.2, and it should be more efficient than the solutions that use Java Collections.
Of course, if your "x", "y", and "z" are all single characters, and a is also a character, you can use if (0 <= "xyz".indexOf(a)) { ... } or
switch (a) {
case 'x': case 'y': case 'z':
// Do something
}
If x,y,z... is Consecutiveļ¼Œ you can use if(a >= 'x' && a <= '...'), if not, you can use ArrayList or just Arrays.
I think that cleanest and fastest way is to put values in array.
String[] values={"value1","value2","value3"};
for (string value : values) {
if (a.equals(value){
//Some code
}
}

Categories