iT邦幫忙

1

JAVA 函數整合問題

以下兩個函數,能整合為一個嗎?

public List<String> getRandom1Ary(ArrayList<ExamItemsBean> items, int count)
{
    List<String> resultAry = new ArrayList<String>();
    Random random = new Random();
    do
    {
        int next = random.nextInt(items.size());
        ExamItemsBean item = items.get(next);
        if (!resultAry.contains(item.getAA()))
        {
            resultAry.add(item.getAA());
        }
    } while (resultAry.size() < count);
    return resultAry;
}

public List<String> getRandom2Ary(ArrayList<ExamItemsBean> items, int count)
{
    List<String> resultAry = new ArrayList<String>();
    Random random = new Random();
    do
    {
        int next = random.nextInt(items.size());
        ExamItemsBean item = items.get(next);
        if (!resultAry.contains(item.getBB()))
        {
            resultAry.add(item.getBB());
        }
    } while (resultAry.size() < count);
    return resultAry;
}
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
dragonH
iT邦超人 5 級 ‧ 2019-08-23 11:15:03
最佳解答

鍵盤解題

要改的應該是

item.getXX()

這個 function

如果可以改成傳參的話

然後在呼叫 getRandomAry 時

把參數帶進去

public List<String> getRandomAry(ArrayList<ExamItemsBean> items, int count, String target)
{
    List<String> resultAry = new ArrayList<String>();
    Random random = new Random();
    do
    {
        int next = random.nextInt(items.size());
        ExamItemsBean item = items.get(next);
        if (!resultAry.contains(item.getItem(target)))
        {
            resultAry.add(item.getItem(target));
        }
    } while (resultAry.size() < count);
    return resultAry;
}

僅供參考

沒測試過 /images/emoticon/emoticon48.gif

原來如此,還有這招~
/images/emoticon/emoticon12.gif

dragonH iT邦超人 5 級 ‧ 2019-08-23 11:19:41 檢舉

/images/emoticon/emoticon82.gif

0
e6319a5b
iT邦新手 4 級 ‧ 2019-08-23 16:53:15
public class MethodAsParams {
	//https://www.rgagnon.com/javadetails/java-0031.html
	public static void main(String s[]) throws Exception {
		// we assume that called methods have no argument
		Object paramsObj[];

		String[]hiStrings={"hi",",","hello"," ","World!!!"};

		paramsObj =new Object[]{hiStrings};
		
		Method thisMethod = Execute.class.getDeclaredMethod("go", paramsObj.getClass());//只有getClass(得到類型) 不是實例
		
		new UseMethodAsParaments(thisMethod, new Execute(), paramsObj);		
		
	}
	



}
class UseMethodAsParaments{
	Method method;
	Execute e;
	public UseMethodAsParaments(Method method,Object e,Object[]objs) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		this.method=method;
		method.invoke(e, objs);
	}
}
class Execute{
	public void go(Object[] args){
		System.out.print("work	");
		for (int i = 0; i < args.length; i++) {
			System.out.print(args[i]);
			
		}
	}
}

這是我平常拿來筆記的程式碼,這是委派,白話一點就是把方法當成參數傳遞
我之前使用此方法,把學校教授的程式碼縮短9倍(當然教授要教學生要用簡單一點的方式)
可以考慮看看

看更多先前的回應...收起先前的回應...

兩個問題,類別好像需要再增加? 另外用我上面的例子,該怎麼調整?

e6319a5b iT邦新手 4 級 ‧ 2019-08-24 13:06:02 檢舉

1.不需要
2.

public class MethodAsParams {
	//https://www.rgagnon.com/javadetails/java-0031.html
	public static void main(String s[]) throws Exception {
		// we assume that called methods have no argument

		List<ExamItemsBean>examItemsBeanList=new ArrayList<ExamItemsBean>();
		for (int i = 0; i < 50; i++) {
			ExamItemsBean tempBean=new ExamItemsBean();
			examItemsBeanList.add(tempBean);
			tempBean.Acontent=String.valueOf(i);
			tempBean.Bcontent=String.valueOf(i+100);
			
		}
		

		
		List<String>temp4Show=examItemsBeanList.get(0).getRandom1Ary(examItemsBeanList, 30, "getLargeThan100");
		for (String string : temp4Show) {
			System.out.print(string+"\n");
		}
		
	}
	



}

class ExamItemsBean{
	
	public String Acontent="",Bcontent="";	
	
	String getSmallThan50() {
		return Acontent;
	}
	String getLargeThan100() {
		return Bcontent;
	}
	
	public List<String> getRandom1Ary(List<ExamItemsBean> items, int count,String methodName) throws NoSuchMethodException, SecurityException
	{
		Method thisMethod = ExamItemsBean.class.getDeclaredMethod(methodName, null);
	    List<String> resultAry = new ArrayList<String>();
	    Random random = new Random();
	    do
	    {
	        int next = random.nextInt(items.size());
	        ExamItemsBean item = items.get(next);
	        try {
				if (!resultAry.contains((String)thisMethod.invoke(item, null)))
				{
				    resultAry.add((String) thisMethod.invoke(item, null));
				}
			} catch (IllegalAccessException e) {
				// TODO 自動產生的 catch 區塊
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO 自動產生的 catch 區塊
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO 自動產生的 catch 區塊
				e.printStackTrace();
			}
	    } while (resultAry.size() < count);
	    return resultAry;
	}
	
}

我蠻久沒寫java了,我剛實驗跑得出來 但版本不太一樣
不知道你的行不行@@ 因為我上面的兩個類別的寫法其實可以改造成你需要也較美觀的,但你好像比較偏好少類別的,獻醜了
我認為我的寫法非常不漂亮 只是想寫出他的功能
如果要求漂亮點可能要自己上網學委派了

感覺你的像是get的時候才區分開? 是想要在set的時候就區分了,也不是偏好,類別一多相對就會複雜,必須很清楚每個類別之間的關係,像設計模式是很頭痛的東西,要能靈活應用

e6319a5b iT邦新手 4 級 ‧ 2019-08-25 16:55:48 檢舉

不好意思@@,看不太懂您的意思 我上述的程式碼只要在做些改變你就能決定你要在何時區分了 畢竟你就只要把此方法想像成你可以把方法當成參數般傳遞就可以了

0
史帝夫
iT邦新手 3 級 ‧ 2019-08-27 12:26:15

若是支援 JAVA8 可使用 Function 方式整合
https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html

//使用方式
getRandomAry(items, 0, bean -> bean.getAA());
getRandomAry(items, 0, bean -> bean.getBB());
getRandomAry(items, 0, bean -> bean.getCC());
//增加 function 參數
public static List<String> getRandomAry(ArrayList<ExamItemsBean> items, int count, Function<ExamItemsBean,String> function) {
    List<String> resultAry = new ArrayList<String>();
    Random random = new Random();
    do {
        int next = random.nextInt(items.size());
        ExamItemsBean item = items.get(next);
        if (!resultAry.contains(function.apply(item))) {
            resultAry.add(function.apply(item));
        }
    } while (resultAry.size() < count);
    return resultAry;
}

用java 8 會不會有android版本過新,太多手機不支援的問題?

史帝夫 iT邦新手 3 級 ‧ 2019-08-29 09:29:27 檢舉

https://developer.android.com/studio/write/java8-support
可以確認看看對應的 SDK 版本;至於大多手機是否支援,就看你使用的版本決定了。

0
matthung
iT邦新手 5 級 ‧ 2019-12-15 11:46:25

Java 函數(方法)整合問題
你應該只要把方法改為只要傳入要隨機取得的元素陣列就好了。

    public static <E> List<E> getRandomAry(List<E> list, int count) {
        if (list == null || list.size() < 1) {
            return new ArrayList<E>();
        }

        List<E> arr = new ArrayList<E>();
        Random random = new Random();
        do {
            int next = random.nextInt(list.size());
            E e = list.get(next);
            if (!arr.contains(e)) {
                arr.add(e);
            }
        } while (arr.size() < count);
        return arr;
    }

我要發表回答

立即登入回答