473,407 Members | 2,598 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

Passing "<", ">", "=", etc as an argument to a method?

Hello,

I am just learning Java and am trying to write a method that does
something like

//===========================================
public Static List find(double[] array,double val,String relationalOp)
{

List list = new ArrayList();
for (int m = 0;m < array.length;m++) {
// The following line is the problem
if (array[m] relationalOp val) {
list.add(array[m]);
}
}
return list;
}
//===========================================

Is it possible to use an argument directly in an if statement like
that?

I am trying to avoid having to rewrite the same method over and over
again, once for each relational operator "==", "<", ">", "<=", ">=",
not to mention all of their "not" versions.

What is the best way to do this?

Thank you for any help.

Eric
Jul 17 '05 #1
5 2778

"Eric A. Forgy" <fo***@uiuc.edu> wrote in message
news:3f**************************@posting.google.c om...
Hello,

I am just learning Java and am trying to write a method
that does something like

//===========================================
public Static List find(double[] array,double val,String relationalOp)
{

List list = new ArrayList();
for (int m = 0;m < array.length;m++) {
// The following line is the problem
if (array[m] relationalOp val) {
list.add(array[m]);
}
}
return list;
}
//===========================================

Is it possible to use an argument directly in an if statement
like that?

No, it is not possible in languages like Java, C++, or C#, but it *is*
possible in some scripting languages.

I am trying to avoid having to rewrite the same method
over and over again, once for each relational
operator "==", "<", ">", "<=", ">=", not to mention all
of their "not" versions.

What is the best way to do this?


You need to map each operator string to a method that performs the required
task, and to which you also pass the required arguments [or, in this case,
operands]. You can design a solution varying in complexity and
sophistication; probably the very simplest is something like:

if (relationalOp.equals("<"))
doLessThan(value1, value2)
else if (relationalOp.equals("="))
doEquals(value1, value2)
...

You get the picture, I'm sure.

I hope this helps.

Anthony Borla

Jul 17 '05 #2
While it was 28/11/03 1:37 am throughout the UK, Anthony Borla sprinkled
little black dots on a white screen, and they fell thus:

<snip>
if (relationalOp.equals("<"))
doLessThan(value1, value2)
else if (relationalOp.equals("="))
doEquals(value1, value2)
...


Why not make relationalOp a number, and save the overhead of doing
string comparison?

Define

final static int EQ = 1;
final static int GT = 2;
final static int GTEQ = 3;
final static int LT = 4;
final static int LTEQ = 5;
final static int NOTEQ = 6;

and pass these values in.

Stewart.

--
My e-mail is valid but not my primary mailbox, aside from its being the
unfortunate victim of intensive mail-bombing at the moment. Please keep
replies on the 'group where everyone may benefit.
Jul 17 '05 #3

"Stewart Gordon" <sm*******@yahoo.com> wrote in message
news:bq**********@sun-cc204.lut.ac.uk...
While it was 28/11/03 1:37 am throughout the UK, Anthony
Borla sprinkled little black dots on a white screen, and they
fell thus:

<snip>
if (relationalOp.equals("<"))
doLessThan(value1, value2)
else if (relationalOp.equals("="))
doEquals(value1, value2)
...


Why not make relationalOp a number, and save the overhead
of doing string comparison?

Define

final static int EQ = 1;
final static int GT = 2;
final static int GTEQ = 3;
final static int LT = 4;
final static int LTEQ = 5;
final static int NOTEQ = 6;

and pass these values in.


Indeed, I fully agree ! However, my response was tailored to the OP's code:
'relationalOp' was a 'String' type.

I *did*, however, mention that:

'You can design a solution varying in complexity and
sophistication...'

and your solution is, most certainly, in this latter group :) !

Cheers,

Anthony Borla
Jul 17 '05 #4
Stewart Gordon wrote:
While it was 28/11/03 1:37 am throughout the UK, Anthony Borla sprinkled
little black dots on a white screen, and they fell thus:

<snip>
if (relationalOp.equals("<"))
doLessThan(value1, value2)
else if (relationalOp.equals("="))
doEquals(value1, value2)
...

Why not make relationalOp a number, and save the overhead of doing
string comparison?

Define

final static int EQ = 1;
final static int GT = 2;
final static int GTEQ = 3;
final static int LT = 4;
final static int LTEQ = 5;
final static int NOTEQ = 6;

and pass these values in.


Even better: use polymorphism. E.g.

// WARNING: Uncompiled, untested code
public class Helper
{
public static final Finder EQUALS = new EqualsFinder();
public static final Finder GREATER_THAN = new GreaterThanFinder();
// etc.

public static List find(double[] array, double val, Finder finder)
{
List result = new ArrayList();
for (int i = 0; i < array.length; i++)
{
if (finder.satisfies(array[i], val))
{
result.add(new Double(array[i]));
}
}
}

public static interface Finder
{
public boolean satisfies(double candidate, double val);
}

public static class EqualsFinder
{
public boolean satisfies(double candidate, double val)
{
return (candidate == value);
}
}

public static class GreaterThanFinder
{
public boolean satisfies(double candidate, double val)
{
return (candidate > value);
}
}

}

Ray

Jul 17 '05 #5

Hi Eric,
I am just learning Java and am trying to write a method that does
something like

//===========================================
public Static List find(double[] array,double val,String relationalOp)


It's a good example method. Unfortunately, Java is not very good at
handling such cases, because it does not treat methods (or operations)
as normal values. You cannot directly pass a method as an argument to
another method.

The closest you could get would be to use anonymous classes as a
substitute, as in the following (beware, very verbose)!

import java.util.*;

public class Main {

abstract static class DoubleOp
{
abstract boolean test(double x, double y);
}

public static List find(double[] array,double val, DoubleOp op){
List list = new ArrayList();
for (int m = 0;m < array.length;m++) {
// The following line is the problem
if (op.test(array[m], val)) {
list.add(new Double(array[m]));
}
}
return list;
}

public static void main(String[] args) {
double[] numbers = new double[]{ -10, -1, 0, 2, 5, 11 };

DoubleOp leq = new DoubleOp() {
boolean test(double x, double y) {
return x < y;
}
};
List negative = find(numbers, 0, leq);
System.out.println("Negative numbers: " + negative);

DoubleOp neq = new DoubleOp() {
boolean test(double x, double y) {
return x != y;
}
};
List nonZero = find(numbers, 0, neq);
System.out.println("Non-zero numbers: " + nonZero);
}
}
It is much easier if you can use a language that support methods as
values. For instance, here is the same code in the Nice language, which
is an extension of Java with many features, including method values (I
am one of the developers of Nice. You can find more about it at
http://nice.sf.net)

List<double> find(double[] array,double val,(double,double)->boolean op)
{
List<double> list = new ArrayList();
for (int m = 0;m < array.length;m++) {
// The following line was the problem
if (op(array[m], val)) {
list.add(array[m]);
}
}
return list;
}

void main(String[] args)
{
double[] numbers = [ -10, -1, 0, 2, 5, 11 ];

let negative = find(numbers, 0, (double x,double y)=> x < y);
System.out.println("Negative numbers: " negative);

let nonZero = find(numbers, 0, (double x,double y)=> x != y);
System.out.println("Non-zero numbers: " nonZero);
}
Some comments:

(double,double)->boolean
This is the type of a method, which has two arguments of type
double, and returns a boolean.

let negative =
This is a way to declare a local variable, letting the compiler
find what is its type.

(double x,double y)=> x < y
This is an expression that represents the '<' comparison on doubles.
One way to generalize your method find is to give it only two arguments:
the array of number, and a method with _one_ argument of type double,
returning a boolean to say if that number should be included in the
results. This generalization is what we call 'filter'. So this code
could be simply rewritten as:

void main(String[] args)
{
double[] numbers = [ -10, -1, 0, 2, 5, 11 ];

let negative = filter(numbers, (double x)=> x < 0);
System.out.println("Negative numbers: " negative);

let nonZero = filter(numbers, (double x)=> x != 0);
System.out.println("Non-zero numbers: " nonZero);
}
Enjoy!

Daniel

The Nice programming language: http://nice.sf.net

Jul 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Son KwonNam | last post by:
When I try <xsl:value-of select="count('/GROUPS/GROUP')"/> on JSTL <x:transform> tag, I got the following error message. org.apache.jasper.JasperException: Can not convert #STRING to a NodeList!...
1
by: Christian Schmidbauer | last post by:
Hello! I prepare my XML document like this way: ------------------------------------------------------- PrintWriter writer; Document domDocument; Element domElement; // Root tag
7
by: Diandian Zhang | last post by:
Does anyone have an idea, how to do it? Thanks in advance!
22
by: Dr Duck | last post by:
GDay all, Something seems odd to me.... I wrote a simple C# function public void bind(ref object a, ref object b, bool atob) { if(atob) b = a; else
3
by: H. S. | last post by:
Hi, I am trying to compile these set of C++ files and trying out class inheritence and function pointers. Can anybody shed some light why my compiler is not compiling them and where I am going...
10
by: Blue® | last post by:
I would like to call the content of content.htm (containing only HTML codes) into index.htm. This is usually done by renaming index.htm to index.shtml and use this tag: <!--#include...
2
by: andrew007 | last post by:
I do xml / xslt transformation using asp.net but I found any value (w/xml format) in xml node html-encoded to &lt and &gt format if it's > or < tag. Since I have sub xml data in a parent xml node...
2
by: Peter Laman | last post by:
In my app I need to dynamically generate a series hyperlinks. Each hyperlink's action must be to focus a field in a <form>. I created the following function to create such a link (the argument is a...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.