Comparing strings inside of two objects - object

I've been trying to compare the string inside of the Card() object with the other Card() objects to check for duplicates when the playing cards are dealt.
Except when printing out the compare statement i'm getting something like Card#97sd829. I made my own Equals() method for comparison of the object Card() inside of the Class but still to no avail.
I've tried using the override of the equals() object but I'm getting an error saying it needs to be inside of a superclass?
public static boolean Equals(Card a, Card b) {
String str1 = a.toString();
String str2 = b.toString();
if (str1.equals(str2))
return true;
else
return false;
}
public static boolean checkDuplicate (Card a, Card b, Card c, Card d, Card e){
int num = 5;
boolean bool = true;
if (Card.Equals(a, b)||Card.Equals(a, c)||Card.Equals(a, d)||Card.Equals(a, e)||
Card.Equals(b, c)||Card.Equals(b, d)||Card.Equals(b, e)||Card.Equals(c, d)||
Card.Equals(c, e)||Card.Equals(d, e)); num--;
if (num == 5)
bool = false;
else
bool = true;
return bool;
}

You are using the toString() method of the Object.class to get a String representation of your cards.
The default implementation of toString() contains the hash of the object. Since you have two different Card-objects the toString() method of these objects produces different output.
A better way would be to implement equals() in the Card class. Then you could check for equality with a.equals(b).
If you want advice how to implement Card.equals() you should post the source code of the Card class.

Related

How can I convert a generic datatype in C#?

See the method below [Not Working as expected].I want double or int as method parameters and return as any data type [in my case return as int,double or string].
Requirement:
if the double or int value is zero then return an empty string else the real int or double value. I don't want to use dynamic as return type
private static T CheckZero<T>( dynamic val ) {
return Math.Sign(val) == 0 ? (T)Convert.ChangeType(string.Empty, typeof(string)) : val;
}

Convert String To Nullable Integer List

I'm wanting to parse a string into a nullable int list in C#
I'm able to convert it to int list bit not a nullable one
string data = "1,2";
List<int> TagIds = data.Split(',').Select(int.Parse).ToList();
say when data will be empty i want to handle that part!
Thanks
You can use following extension method:
public static int? TryGetInt32(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}
Then it's simple:
List<int?> TagIds = data.Split(',')
.Select(s => s.TryGetInt32())
.ToList();
I use that extension method always in LINQ queries if the format can be invalid, it's better than using a local variable and int.TryParse (E. Lippert gave an example, follow link).
Apart from that it may be better to use data.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries) instead which omits empty strings in the first place.

Why String s1==s2 return false if I add +"" and return True If I used s1==s2

public class MainDemo
{
public void comp()
{
String s1 = "abc";
String s2 = "abc";
System.out.print(""+s1==s2); // Why return false??? Plz clear my doubt?
System.out.println(s1==s2);//And why true for this
}
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
MainDemo obj=new MainDemo();
obj.comp();
}
}
#####################################################
Why this return false ??
System.out.print(""+s1==s2); // Why return false???
Please clear my doubt?
Edited
Can someone Tell me how do I check the instance Value
EDITED 2
System.out.println(s1.hashCode()); // BOTH ARE SAME
System.out.println(s2.hashCode());// BOTH ARE SAME
Then What happened to this?????
Comparing String like this is not a good idea, use a1.equals(a2); Well back to answer of your question.
String a1="abc";
String a2="abc";
System.out.println(a1==a2); // true
System.out.println(""+a1==a2); // false
System.out.println(""+(a1==a2)); // true
Look at this ""+a1. If you try ""+a1==a1 it return false, confused? don't be because ""+a1 is just a new String object on heap that points to "abc" in the string pool. while ""+(a1==a2) compares first and than append like this :""+(true)
As I suggested use a1.equals(a2); instead of == with strings
official: here
equals(Object anObject) Compares this string to the specified object.
""+s1 is a new String and so not the same Object as s2. You should you equals to compare values of Strings in Java. For more information and examples have a look at: How do I compare strings in Java?
If I closed the s1==s2 in bracket like this (s1==s2) Its return true.....Confuseed
Well, these parentheses are used to specify operator precendence. Same as in mathematics.
System.out.println("" + (s1 == s2));
That will just do
System.out.println("" + true);
What you had before was equivalent to
System.out.println( ( "" + s1) == s2);
The == operator checks whether the references to the String objects are equal.
And in String.equals(""); checks contains of both Strings.
Please Find my comments in your code.. Also read unicode etc from Core Java by Cay Horstman
public class MainDemo {
public void comp() {
String s1 = "abc";//String s1 "abc"
String s2 = "abc";//String s2 "abc"
System.out.print(""+s1==s2); // Why return false??? Plz clear my doubt? // its "null+abc"=="abc" // mind the null in first "abc" and tell they equal???
System.out.println(s1==s2);//And why true for this // because here its "abc"=="abc" no null added to the string
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MainDemo obj=new MainDemo();
obj.comp();
}
}
String s1 = "abc";
String s2 = "abc";
System.out.print(""+s1==s2); // comparing a reference to object on heap with the reference to interned string in string pool
System.out.println(s1==s2); // comparing references to same interned string in the string pool
String s1 and String s2 are being assigned string literals i-e there value is known at compile time. JVM would intern them in the string pool and both s1 and s2 would actually be pointing to same string in the string pool.
when you do (s1==s2); s1 and s2 both reference to the same string in the string pool so they return true.
but doing (""+s1==s2); returns false because ""+s1 would be evaluated on runtime. JVM would make a string object on the heap that in turn would point to "abc" in the string pool.
enforce string interning using
System.out.println((""+s1).intern() == s2); // true because of explicit interning
Generally, its better to use .equals() to compare strings. If you want to directly compare the strings you must know how JVM is handling strings behind the scenes.
read What is Java String interning? for further clarification.
Because String s1's length got changed now. Check length of those strings using string length function and see what it returns.

How do I use groovy's AS keyword

This may be a duplicate but "as" is an INCREDABLY hard keyword to google, even S.O. ignores "as" as part of query.
So I'm wondering how to implement a class that supports "as" reflexively. For an example class:
class X {
private val
public X(def v) {
val=v
}
public asType(Class c) {
if (c == Integer.class)
return val as Integer
if(c == String.class)
return val as String
}
}
This allows something like:
new X(3) as String
to work, but doesn't help with:
3 as X
I probably have to attach/modify the "asType" on String and Integer somehow, but I feel any changes like this should be confined to the "X" class... Can the X class either implement a method like:
X fromObject(object)
or somehow modify the String/Integer class from within X. This seems tough since it won't execute any code in X until X is actually used... what if my first usage of X is "3 as X", will X get a chance to override Integer's asType before Groovy tries to call is?
As you say, it's not going to be easy to change the asType method for Integer to accept X as a new type of transformation (especially without destroying the existing functionality).
The best I can think of is to do:
Integer.metaClass.toX = { -> new X( delegate ) }
And then you can call:
3.toX()
I can't think how 3 as X could be done -- as you say, the other way; new X('3') as Integer is relatively easy.
Actually, you can do this:
// Get a handle on the old `asType` method for Integer
def oldAsType = Integer.metaClass.getMetaMethod( "asType", [Class] as Class[] )
// Then write our own
Integer.metaClass.asType = { Class c ->
if( c == X ) {
new X( delegate )
}
else {
// if it's not an X, call the original
oldAsType.invoke( delegate, c )
}
}
3 as X
This keeps the functionality out of the Integer type, and minimizes scope of the effect (which is good or bad depending on what you're looking for).
This category will apply asType from the Integer side.
class IntegerCategory {
static Object asType(Integer inty, Class c) {
if(c == X) return new X(inty)
else return inty.asType(c)
}
}
use (IntegerCategory) {
(3 as X) instanceof X
}

C# 4.0 optional out/ref arguments

Does C# 4.0 allow optional out or ref arguments?
No.
A workaround is to overload with another method that doesn't have out / ref parameters, and which just calls your current method.
public bool SomeMethod(out string input)
{
...
}
// new overload
public bool SomeMethod()
{
string temp;
return SomeMethod(out temp);
}
If you have C# 7.0, you can simplify:
// new overload
public bool SomeMethod()
{
return SomeMethod(out _); // declare out as an inline discard variable
}
(Thanks #Oskar / #Reiner for pointing this out.)
As already mentioned, this is simply not allowed and I think it makes a very good sense.
However, to add some more details, here is a quote from the C# 4.0 Specification, section 21.1:
Formal parameters of constructors, methods, indexers and delegate types can be declared optional:
fixed-parameter:
attributesopt parameter-modifieropt type identifier default-argumentopt
default-argument:
= expression
A fixed-parameter with a default-argument is an optional parameter, whereas a fixed-parameter without a default-argument is a required parameter.
A required parameter cannot appear after an optional parameter in a formal-parameter-list.
A ref or out parameter cannot have a default-argument.
No, but another great alternative is having the method use a generic template class for optional parameters as follows:
public class OptionalOut<Type>
{
public Type Result { get; set; }
}
Then you can use it as follows:
public string foo(string value, OptionalOut<int> outResult = null)
{
// .. do something
if (outResult != null) {
outResult.Result = 100;
}
return value;
}
public void bar ()
{
string str = "bar";
string result;
OptionalOut<int> optional = new OptionalOut<int> ();
// example: call without the optional out parameter
result = foo (str);
Console.WriteLine ("Output was {0} with no optional value used", result);
// example: call it with optional parameter
result = foo (str, optional);
Console.WriteLine ("Output was {0} with optional value of {1}", result, optional.Result);
// example: call it with named optional parameter
foo (str, outResult: optional);
Console.WriteLine ("Output was {0} with optional value of {1}", result, optional.Result);
}
There actually is a way to do this that is allowed by C#. This gets back to C++, and rather violates the nice Object-Oriented structure of C#.
USE THIS METHOD WITH CAUTION!
Here's the way you declare and write your function with an optional parameter:
unsafe public void OptionalOutParameter(int* pOutParam = null)
{
int lInteger = 5;
// If the parameter is NULL, the caller doesn't care about this value.
if (pOutParam != null)
{
// If it isn't null, the caller has provided the address of an integer.
*pOutParam = lInteger; // Dereference the pointer and assign the return value.
}
}
Then call the function like this:
unsafe { OptionalOutParameter(); } // does nothing
int MyInteger = 0;
unsafe { OptionalOutParameter(&MyInteger); } // pass in the address of MyInteger.
In order to get this to compile, you will need to enable unsafe code in the project options. This is a really hacky solution that usually shouldn't be used, but if you for some strange, arcane, mysterious, management-inspired decision, REALLY need an optional out parameter in C#, then this will allow you to do just that.
ICYMI: Included on the new features for C# 7.0 enumerated here, "discards" is now allowed as out parameters in the form of a _, to let you ignore out parameters you don’t care about:
p.GetCoordinates(out var x, out _); // I only care about x
P.S. if you're also confused with the part "out var x", read the new feature about "Out Variables" on the link as well.
No, but you can use a delegate (e.g. Action) as an alternative.
Inspired in part by Robin R's answer when facing a situation where I thought I wanted an optional out parameter, I instead used an Action delegate. I've borrowed his example code to modify for use of Action<int> in order to show the differences and similarities:
public string foo(string value, Action<int> outResult = null)
{
// .. do something
outResult?.Invoke(100);
return value;
}
public void bar ()
{
string str = "bar";
string result;
int optional = 0;
// example: call without the optional out parameter
result = foo (str);
Console.WriteLine ("Output was {0} with no optional value used", result);
// example: call it with optional parameter
result = foo (str, x => optional = x);
Console.WriteLine ("Output was {0} with optional value of {1}", result, optional);
// example: call it with named optional parameter
foo (str, outResult: x => optional = x);
Console.WriteLine ("Output was {0} with optional value of {1}", result, optional);
}
This has the advantage that the optional variable appears in the source as a normal int (the compiler wraps it in a closure class, rather than us wrapping it explicitly in a user-defined class).
The variable needs explicit initialisation because the compiler cannot assume that the Action will be called before the function call exits.
It's not suitable for all use cases, but worked well for my real use case (a function that provides data for a unit test, and where a new unit test needed access to some internal state not present in the return value).
Use an overloaded method without the out parameter to call the one with the out parameter for C# 6.0 and lower. I'm not sure why a C# 7.0 for .NET Core is even the correct answer for this thread when it was specifically asked if C# 4.0 can have an optional out parameter. The answer is NO!
For simple types you can do this using unsafe code, though it's not idiomatic nor recommended. Like so:
// unsafe since remainder can point anywhere
// and we can do arbitrary pointer manipulation
public unsafe int Divide( int x, int y, int* remainder = null ) {
if( null != remainder ) *remainder = x % y;
return x / y;
}
That said, there's no theoretical reason C# couldn't eventually allow something like the above with safe code, such as this below:
// safe because remainder must point to a valid int or to nothing
// and we cannot do arbitrary pointer manipulation
public int Divide( int x, int y, out? int remainder = null ) {
if( null != remainder ) *remainder = x % y;
return x / y;
}
Things could get interesting though:
// remainder is an optional output parameter
// (to a nullable reference type)
public int Divide( int x, int y, out? object? remainder = null ) {
if( null != remainder ) *remainder = 0 != y ? x % y : null;
return x / y;
}
The direct question has been answered in other well-upvoted answers, but sometimes it pays to consider other approaches based on what you're trying to achieve.
If you're wanting an optional parameter to allow the caller to possibly request extra data from your method on which to base some decision, an alternative design is to move that decision logic into your method and allow the caller to optionally pass a value for that decision criteria in. For example, here is a method which determines the compass point of a vector, in which we might want to pass back the magnitude of the vector so that the caller can potentially decide if some minimum threshold should be reached before the compass-point judgement is far enough away from the origin and therefore unequivocally valid:
public enum Quadrant {
North,
East,
South,
West
}
// INVALID CODE WITH MADE-UP USAGE PATTERN OF "OPTIONAL" OUT PARAMETER
public Quadrant GetJoystickQuadrant([optional] out magnitude)
{
Vector2 pos = GetJoystickPositionXY();
float azimuth = Mathf.Atan2(pos.y, pos.x) * 180.0f / Mathf.PI;
Quadrant q;
if (azimuth > -45.0f && azimuth <= 45.0f) q = Quadrant.East;
else if (azimuth > 45.0f && azimuth <= 135.0f) q = Quadrant.North;
else if (azimuth > -135.0f && azimuth <= -45.0f) q = Quadrant.South;
else q = Quadrant.West;
if ([optonal.isPresent(magnitude)]) magnitude = pos.Length();
return q;
}
In this case we could move that "minimum magnitude" logic into the method and end-up with a much cleaner implementation, especially because calculating the magnitude involves a square-root so is computationally inefficient if all we want to do is a comparison of magnitudes, since we can do that with squared values:
public enum Quadrant {
None, // Too close to origin to judge.
North,
East,
South,
West
}
public Quadrant GetJoystickQuadrant(float minimumMagnitude = 0.33f)
{
Vector2 pos = GetJoystickPosition();
if (minimumMagnitude > 0.0f && pos.LengthSquared() < minimumMagnitude * minimumMagnitude)
{
return Quadrant.None;
}
float azimuth = Mathf.Atan2(pos.y, pos.x) * 180.0f / Mathf.PI;
if (azimuth > -45.0f && azimuth <= 45.0f) return Quadrant.East;
else if (azimuth > 45.0f && azimuth <= 135.0f) return Quadrant.North;
else if (azimuth > -135.0f && azimuth <= -45.0f) return Quadrant.South;
return Quadrant.West;
}
Of course, that might not always be viable. Since other answers mention C# 7.0, if instead what you're really doing is returning two values and allowing the caller to optionally ignore one, idiomatic C# would be to return a tuple of the two values, and use C# 7.0's Tuples with positional initializers and the _ "discard" parameter:
public (Quadrant, float) GetJoystickQuadrantAndMagnitude()
{
Vector2 pos = GetJoystickPositionXY();
float azimuth = Mathf.Atan2(pos.y, pos.x) * 180.0f / Mathf.PI;
Quadrant q;
if (azimuth > -45.0f && azimuth <= 45.0f) q = Quadrant.East;
else if (azimuth > 45.0f && azimuth <= 135.0f) q = Quadrant.North;
else if (azimuth > -135.0f && azimuth <= -45.0f) q = Quadrant.South;
else q = Quadrant.West;
return (q, pos.Length());
}
(Quadrant q, _) = GetJoystickQuadrantAndMagnitude();
if (q == Quadrant.South)
{
// Do something.
}
What about like this?
public bool OptionalOutParamMethod([Optional] ref string pOutParam)
{
return true;
}
You still have to pass a value to the parameter from C# but it is an optional ref param.
void foo(ref int? n)
{
return null;
}

Resources