Home > Back-end >  Lambda call container object method; Format the name of the class: : common method
Lambda call container object method; Format the name of the class: : common method

Time:10-04

List Heros=new ArrayList (a);
The Random r=new Random ();
for (int i=0; I & lt; 4. I++) {
Heros. Add (new Hero (" Hero "+ I, r.n extInt (1000), r.n extInt (100)));
}
/* * key
System. The out. Println (" method of reference objects in the container: ");
The filter (heros, hero - & gt; Hero. Matched ());
The filter (heros, Hero: : matched);//matched for Hero classes in the ordinary methods;

Problem?? I am calling methods of objects in the container, but matched and is not a static method, how can I use the name of the class: : ordinary method; About the grammar is not very good
Focus on * */

//this is my filtering methods
Public static void filter (List Heros, HeroChecker Hc) {
For (Hero Hero: heros) {
{if (hc) test (hero))
System. The out. Println (hero);
}
}
}


Public interface HeroChecker {
//function between
Public Boolean test (T T);

}

CodePudding user response:

 
Hero Hero=new Hero (null, 0, 0);
The filter (heros, hero: : matched);//to call object method using scope, need the concrete object,

CodePudding user response:

This I know, you said is object method is called, I looked at other people's code today, with the name of the class can call ordinary method, not an error, but I don't know the principle,

<* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * & gt;

Using the Lambda expressions

The filter (heros, h - & gt; H.h p> 100 & amp; & H.d amage<50);


Call in Lambda expressions in a container object Hero method matched

The filter (heros, h - & gt; H.m have ());


Matched just happened to be the Hero's method of objects in the container, then you can further to

The filter (heros, Hero: : matched);


This way is called a reference method of objects in the container

CodePudding user response:

The method and the c + + function pointer is similar, through the interface between transformation, realize the function name as a parameter to the function features,
Is the interface between the conditions of specific types and you need to call object method at the same class, she just HeroChecker< code; T> The T type of Hero and interface methods needs to receive a Hero type of object as a parameter,
 
The class Adder
{
int i;
Int j;

Public Adder (int, int j)
{
This i.=I;
This. J=j;
}

Public int the add ()
{
The return I + j;
}
}

Interface AddInterface
{
Public int result (T T);
}

Public class ThreadState
{
Public static void main (String [] args)
{
Adder obj=new Adder (11, 22);
Int res=getRes (obj, Adder: : add);//33
}

Public static int getRes (Adder add, AddInterface Ops)
{
Return the ops. The result (add);
}

}
  • Related