472,378 Members | 1,301 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,378 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 2686

"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: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
2
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
1
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
0
by: F22F35 | last post by:
I am a newbie to Access (most programming for that matter). I need help in creating an Access database that keeps the history of each user in a database. For example, a user might have lesson 1 sent...

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.